0

我在 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);
}

为什么会这样?我错过了什么?

4

1 回答 1

1

您应该包含 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>

于 2018-07-03T22:14:37.700 回答