简体   繁体   中英

Adding a scale to canvas image zoom

I'm using a some code from https://github.com/dimxasnewfrozen/Panning-Zooming-Canvas-Demos/blob/master/demo12/main.js (demo at http://dayobject.me/canvas/demo12/ ) to zoom in on an image using the Canvas element.

However, when zooming the jump between one zoom level and the next is too large, so I need to add a scale parameter.

How would I got about doing this?

It seams to me as if the algorithm always takes half of the dimension befor the zoom. At the end of you code you see it in main.js the mouseWheel function:

initialImageWidth = initialImageWidth * 2;

the width is divided by 2 so just change the used value.

You said the step used to zoom in and out is too big.

So I suggest that you generate the new value by using the dimensions of the image you want to zoom. For example you take a percentage of the biggest dimension of the current image.

That's how you can implement a zoom function that zooms according to the dimensions of the image

In your main.js , you can change your zoomLevel here,

mouseWheel: function (e) {
    e.preventDefault() // Please add this, coz the scroll event bubbles up to document.
    var zoomLevel = 2;

    ...

    if (delta > 0) 
    {   
        // ZOOMING IN
        var zoomedX = canvasPos.deltaX - (canvasZoomX - canvasPos.deltaX);
        var zoomedY = canvasPos.deltaY - (canvasZoomY - canvasPos.deltaY);

        // scale the image up by 2
        initialImageWidth = initialImageWidth * zoomLevel;
    }
    else
    {   
        // ZOOMING OUT
        var zoomedX = (canvasPos.deltaX + canvasZoomX);
        var zoomedY = (canvasPos.deltaY + canvasZoomY);

        // scale the image down by 2
        initialImageWidth = initialImageWidth / zoomLevel;

    }
}

Disclaimer: this ruins the zoomedX and zoomedY values. You gotta fix them :)

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