简体   繁体   English

无法清除 HTML5 中的画布

[英]Can't clear canvas in HTML5

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.我在 HTML 页面中有几个画布分层,我希望能够更改顶层,它显示用户可以选择的图像。

The problem is, whenever I call clearRect it does clear the canvas for a moment, then the previous image is loaded back.问题是,每当我调用 clearRect 时,它都会暂时清除画布,然后重新加载上一个图像。

This is my javascript code:这是我的 javascript 代码:

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.您应该包含 HTML 代码,因为它有点不清楚您的问题是什么,但这是我想出的。

"WIDTH" and "HEIGHT" might be the troublemakers here. “宽度”和“高度”可能是这里的麻烦制造者。 Have you tried replacing them with canvas.width and canvas.height?你有没有试过用 canvas.width 和 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM