0

I have a couple of canvas layered in a HTML page, I want to be able to change the top layer, which shows images that the user can select.

The problem is, whenever I call clearRect it does clear the canvas for a moment, then the previous image is loaded back.

This is my javascript code:

window.onload = function(){
    init();
    drawAll();  
}
function clear(){
    ctx2.clearRect(0,0,WIDTH,HEIGHT);
}

function init() {
    city.src ="city.png";
    image2.src="image.png";
    layer1 = document.getElementById("layer1");
    ctx1 = layer1.getContext("2d");
    layer2 = document.getElementById("layer2");
    ctx2 = layer2.getContext("2d");
}


function drawAll() {
    draw1();
    draw2();
}

function draw2() {
    ctx2.clearRect(0,0,WIDTH,HEIGHT);
    ctx2.drawImage(image2, 240, 200);
}

function draw1() {
    ctx1.clearRect(0, 0, WIDTH, HEIGHT);
    ctx1.drawImage(city, 0, 0);
}

Why is this happening? What am I missing?

Jonas
  • 121,568
  • 97
  • 310
  • 388
M Rajoy
  • 4,028
  • 14
  • 54
  • 111

1 Answers1

1

You should have included the HTML code because it's kinda unclear what your problem is, but here's what I came up with.

"WIDTH" and "HEIGHT" might be the troublemakers here. Have you tried replacing them with canvas.width and canvas.height?

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#F00";
  ctx.fillRect(0, 0, 320, 180);
}

draw();
<canvas id="myCanvas" width=400 height=400></canvas>
Sufi2425
  • 59
  • 6