[英]Can't clear canvas in HTML5
我在 HTML 頁面中有幾個畫布分層,我希望能夠更改頂層,它顯示用戶可以選擇的圖像。
問題是,每當我調用 clearRect 時,它都會暫時清除畫布,然后重新加載上一個圖像。
這是我的 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);
}
為什么會這樣? 我錯過了什么?
您應該包含 HTML 代碼,因為它有點不清楚您的問題是什么,但這是我想出的。
“寬度”和“高度”可能是這里的麻煩制造者。 你有沒有試過用 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.