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?
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.