如何限制HTML5画布上下文比例?

时间:2015-09-18 12:24:16

标签: javascript html5 canvas scale

我正在缩放加载到html5画布中的图像但是我没有设置缩放限制(例如宽度> 200和<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;
    };

那么如何获得上下文的实际大小? - 然后我可以检查

if (scale) factor*contextWidth 

小/大并采用因子...

2 个答案:

答案 0 :(得分:0)

图像尺寸是缩放尺寸。

// 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

获得您想要的最大比例

// 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

答案 1 :(得分:0)

我自己解决了这个问题:

    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);
...