HTML5画布再次缩放绘制

时间:2015-01-08 16:42:14

标签: javascript html5 canvas draw

目前我正在尝试制作画布缩放并再次绘制整个画布

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;

    });

事情是行不通的。 Canvas永远不会更新...变量似乎很好,因为我需要再次绘制整个画布我将所有数据保存到数组中

1 个答案:

答案 0 :(得分:1)

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