Place background image in HTML canvas

Asked

Viewed 3,130 times

2

I’m trying to learn a little more about canvas for Html5 games.

var canvas;//o elemento canvas sobre o qual desenharemos
var ctx;//o "contexto" da canvas que será utilizado (2D ou 3D)
var dx = 5;//a tava de variação (velocidade) horizontal do objeto
var dy = 5;//a tava de variação (velocidade) vertical do objeto
var x = 250;//posição horizontal do objeto (com valor inicial)
var y = 100;//posição vertical do objeto (com valor inicial)
var WIDTH = 500;//largura da área retangular
var HEIGHT = 200;//altura da área retangular

function Desenhar() {
    ctx.beginPath();
    ctx.fillStyle = "blue";
    ctx.arc(x, y, 10, 0, Math.PI*2, true);
    ctx.fill();
}

function LimparTela() {
    ctx.fillStyle = "white";
    ctx.strokeStyle = "black";
    ctx.beginPath();
    ctx.rect(0, 0, WIDTH, HEIGHT);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
}

function Iniciar() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    return setInterval(Atualizar, 10);
}

function KeyDown(evt){
    switch (evt.keyCode) {
        case 38:  /*seta para cima */
            if (y - dy > 0){
                y -= dy;
            }
            break;
        case 40:  /*set para baixo*/
            if (y + dy < HEIGHT){
                y += dy;
            }
            break;
        case 37:  /*set para esquerda*/
            if (x - dx > 0){
                x -= dx;
            }
            break;
        case 39:  /*seta para direita*/
            if (x + dx < WIDTH){
                x += dx;
            }
            break;
    }
}

function Atualizar() {
    LimparTela();    
    Desenhar();
}
window.addEventListener('keydown', KeyDown, true);
Iniciar();
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Canvas</title>
</head>
<body>
    <div>
        <canvas id="canvas" width="500" height="200">
        Se você visualizar esse texto, seu browser não suporta a tag canvas.
        </canvas>
    </div>
    <script type="text/javascript" src="desenhar_circulo.js"></script>
</body>
</html>

I would like to insert a background IMAGE(png) into the canvas. Since: I tried using css in index.html, gave black screen by conflict.

<style>
    canvas{
        background-image: url("fundo.png");
    }
</style>

I also tried to draw a background image as the player. Gave conflict also.

I believe the problem/solution is in:

ctx.fillStyle = "white";

Any suggestions?

1 answer

2


I solved this, I’ll leave it here for if one day someone needs <3

Create the background function():

function fundo(){
    fundoImg.src = "fundo.png";
    ctx.drawImage(fundoImg, 0, 0);  
}

Add this at the end of the Cleanup function

fundo();

Remember to create the variable at the beginning:

var fundoImg = new Image();

Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.