目前,我正在尝试放大画布,并再次绘制整个画布
var painter = document.getElementById('painter');
var cp = painter.getContext('2d');
var scale = 1;
var originx = 0;
var savedData = [];
var originy = 0;
var zoom = 0;
$('#painter').on('mousewheel', function(event) {
var imgData = cp.getImageData(0, 0, painter.width, painter.height);
savedData.push(imgData);
var mousex = event.clientX - painter.offsetLeft;
var mousey = event.clientY - painter.offsetTop;
var wheel = event.deltaY;//n or -n
var zoom = 1 + wheel/2;
cp.translate(
originx,
originy
);
cp.scale(zoom,zoom);
cp.translate(
-( mousex / scale + originx - mousex / ( scale * zoom ) ),
-( mousey / scale + originy - mousey / ( scale * zoom ) )
);
if (savedData.length > 0) {
var imgData = savedData.pop();
cp.putImageData(imgData, 0, 0);
}
originx = ( mousex / scale + originx - mousex / ( scale * zoom ) );
originy = ( mousey / scale + originy - mousey / ( scale * zoom ) );
scale *= zoom;
});
事情是行不通的。画布永远不会更新...变量似乎很好,因为我需要再次绘制整个画布,因此我将所有数据保存到数组中
最佳答案
getImageData & context.putImageData
是非常昂贵的操作。
相反,您可以将原始内容存储在使用创建的第二个仅限内存的画布中
var secondCanvas = document.createElement('canvas')
var secondContext = secondCanvas.getContext('2d');
secondCanvas.width=mainCanvas.width;
secondCanvas.height=mainCanvas.height;
secondContext.drawImage(mainCanvas,0,0);
然后将第二个画布用作您在主画布上的缩放绘图的图像源:
mainContext.drawImage(secondCanvas,x,y);
将内容缓存到第二个画布后,可以使用此Stackoverflow答案用鼠标滚轮进行缩放:
Zoom and pan in animated HTML5 canvas