调整画布大小并重新定位图像大小

时间:2017-08-31 06:22:04

标签: javascript html5 canvas

我有一个用坐标绘制在画布上的图像。例如;

var data = {
 x: 100, y: 100, // the coord when the image drawn
 src: imguri, 
 scale: 1.6 // the scale when the image drawn
}

和缩放功能如下;

var scale = 1.6, width = canvas.width, height = canvas.height

function zoom(positiveOrNegative) {
 scale += positiveOrNegative * .2
 canvas.width = width * scale
 canvas.height = height * scale
 loadImage() 
}

function loadImage() {
 var img = new Image()
 img.src = data.src;
 img.onload = function() { context.drawImage(img, data.x, data.y) }
}

https://jsfiddle.net/bbuv53u6/

如何在调整画布大小时将图像调整大小并重新定位,使其看起来像是放大/缩小了?

1 个答案:

答案 0 :(得分:0)

使用此方法获取位置值。

如果你只是

var posX = 10

此变量已修复,但如果您不使用变量使用方法:

 VIEW.W(2)  // this is 2% from window width . 

在这种情况下,您无需对调整大小进行任何计算。 此外,您的示例没有缩放效果,您只需调整canvas标记元素的大小。

缩放程序:

   //context.save();
   context.translate( x , y );
   context.scale(scale, scale); 
   //context.restore();

Heres对象:

var VIEW = {

 W :  function(per){

    if (typeof per === 'undefined'){
        return window.innerWidth;
    }else{
        return window.innerWidth/100 * per;
    }

 },
 H :  function(per){

    if (typeof per === 'undefined'){
        return window.innerHeight;
    }
    else{
        return window.innerHeight/100 * per;
    }

},

ASPECT : function(){

    return window.innerWidth / window.innerHeight;

},

};

奖金链接:

Zooming with canvas