html5:将画布复制到图像并返回 [英] 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.
我需要一种方法将画布复制到图像对象,然后将图像复制回画布而不降低质量.将画布复制到 javascript 变量,以及稍后将此变量复制回画布的具体方法是什么?
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.
谢谢,
推荐答案
drawImage() 方法可以使用另一个画布而不是图像绘制到画布上.
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.
例如
// 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);
这篇关于html5:将画布复制到图像并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!