Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I implemented a zoom in and out function on a canvas element. it works by scaling the canvas, translating it, and then redraw the whole scene again. the problem is that it takes a lot of time to redraw everything because i got a lot of things on my canvas.

I need a way to copy the canvas to an image object and than copy the image back to the canvas without loosing quality. what are the specific methods to copy canvas to a javascript variable, and to to copy this variable back to the canvas later?

I'll be glad if you write down the code because I couldn't find any good explanation over the internet.

thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
282 views
Welcome To Ask or Share your Answers For Others

1 Answer

The drawImage() method can draw to a canvas using another canvas instead of an image.

You could create a 'backup' canvas, of the same size as your original, draw the first one to there and then draw that one back to the original when you need it.

e.g.

// Assume we have a main canvas
// canvas = <main canvas>
ctx = canvas.getContext('2d');
..

// create backing canvas
var backCanvas = document.createElement('canvas');
backCanvas.width = canvas.width;
backCanvas.height = canvas.height;
var backCtx = backCanvas.getContext('2d');

// save main canvas contents
backCtx.drawImage(canvas, 0,0);

..

// restore main canvas
ctx.drawImage(backCanvas, 0,0);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...