简体   繁体   中英

HTML5 canvas zoom draw again

Currently im trying to make a canvas zoom and also draw again the whole canvas

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;

    });

Thing is it does not work. Canvas is never updated... the variables seems to be fine and since I need to draw again the whole canvas Im saving all the data into an array

getImageData & context.putImageData are very expensive operations.

Instead, you could store your original content in a second in-memory-only canvas created with

var secondCanvas = document.createElement('canvas')
var secondContext = secondCanvas.getContext('2d');
secondCanvas.width=mainCanvas.width;
secondCanvas.height=mainCanvas.height;
secondContext.drawImage(mainCanvas,0,0);

Then use that second canvas as an image source for your scaled drawing on the main canvas:

mainContext.drawImage(secondCanvas,x,y);

Once you have your content cached to a second canvas, you can use this Stackoverflow answer to zoom with the mousewheel:

Zoom and pan in animated HTML5 canvas

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM