简体   繁体   中英

how to limit HTML5 canvas context scale?

I'm scaling the image loaded into an html5 canvas but I con't set limits for scale (eg width > 200 and < 1900):

    var zoom = function(clicks){
        var pt = ctx.transformedPoint(lastX,lastY);
        ctx.translate(pt.x,pt.y);
        var factor = Math.pow(scaleFactor,clicks);
        ctx.scale(factor,factor);
        ctx.translate(-pt.x,-pt.y);

        redraw();
    }

    var handleScroll = function(evt){
        var delta = evt.wheelDelta ? evt.wheelDelta/40 : evt.detail ? -evt.detail : 0;
        document.querySelector('#brightness-value').value = 0;
        document.querySelector('#contrast-value').value = 0;
        document.querySelector('#brightness').value = 0;
        document.querySelector('#contrast').value = 0;
        if (delta) zoom(delta);

        return evt.preventDefault() && false;
    };

So how do I get the actual size of the context? - then I could check

if (scale) factor*contextWidth 

ist to small/big and adopt factor...

The image size is the scaled size.

// img is an image object
// ctx is context
// scale is scaling
ctx.setScale(scale,scale);
var displayWidth = image.width * scale; // the display width.
var displayHeight = image.height * scale; // the display height

To get the max scale you want

// maxImgW the max width you want
var maxImgW = 1900;  
var maxScale = maxImgW / image.width; // the scale that will get the max size
var minImgW = 200;
var minScale = minImgW / image.width; // the scale that will get the min size

Solved it myself similiar:

    imgRes.src = "img/01_cc.jpg";
    var sizeX = imgRes.width;
    var sizeY = imgRes.height;
...
            oldsizeX = sizeX;
            oldsizeY = sizeY;
            sizeX = sizeX * factor;
            sizeY = sizeY * factor;

            // Limit für Skalierung
            if (sizeX <= 910) {
                factor = 910 / sizeX;
                if (factor > 1) factor = 1;
            }
            if (sizeX >= 4550) {
                factor = 4550 / sizeX;
                if (factor < 1) factor = 1;
            }
            sizeX = oldsizeX * factor;
            sizeY = oldsizeY * factor;
            // console.log(sizeX+" - "+sizeY+" - "+factor);
            ctx.scale(factor, factor);
...

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