开发者

Can I draw upon a canvas element without destroying what was previously drawn upon it?

Say I want to draw something upon a canvas:

function draw() {

    var canvas = document.getElementById('myCanvas');

    ctx = canvas.getContext('2d');
    ctx.canvas.width = 100;
    ctx.canvas.height = 100;

    ctx.fillStyle = 'red';

    ctx.fillRect(0, 0, 50, 50);

}

But then at a later date I want to draw something else on it,

function drawMore() {

    var canvas = document.getElementById('myCanvas');

    ctx = canvas.getContext('2d');
    ctx.canvas.width = 100;
    ctx.canvas.height = 100;

    ctx.fillStyle = 'blue';

    ctx.fillRect(50, 50, 50, 50);

}

Is there anyway I can do this without destroying the previously drawn blue-block, without having to explicitly redraw the previous content (say for example, I don't actually kn开发者_StackOverflow社区ow what's upon it).

Thanks!


Delete these lines:

ctx.canvas.width = 100;
ctx.canvas.height = 100;

You don't need to reset the height and width each time. Example

Setting the width is actually a trick for clearing the canvas.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜