Joshua
Joshua

Reputation: 6665

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 know what's upon it).

Thanks!

Upvotes: 1

Views: 101

Answers (1)

Joe
Joe

Reputation: 82594

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.

Upvotes: 3

Related Questions