Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

html - html5: copy a canvas to image and back

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

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

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...