Search code examples
javascripthtml5-canvaspositionmousescale

Mouse position after scaling image (ratioX/ratioY)


If you click the mouse, the image will be cropped by the position of the Y mouse: https://jsfiddle.net/1mL9qfmd/2/ (gif: http://wgrajo.pl/img/ezgif4baa2da6575.gif)

html:

<canvas id="game" width="640" height="480" style="position: absolute; left:0px; top:0px; border:1px red solid;"></canvas>

javascript:

var img = new Image;
    img.src = 'http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg';
var ctx = game.getContext('2d');
var ratioX = 2700/2300;
var ratioY = 1300/1080;
var cutY = 87;
var mouse = {y: 0, x: 0};

setInterval(function(){
   ctx.clearRect(0,0,game.width, game.height);
   ctx.drawImage(img, 0,0, img.width, img.height-cutY, 0, 0, img.width, img.height-cutY);
},1000/60);

window.addEventListener('mousedown', function(e){
   mouse.y = e.pageY;
   mouse.x = e.pageX;

   cutY = Math.abs(img.height-mouse.y);
}, false);

But when I add image scaling to drawImage (ratioX / ratioY)

ctx.drawImage(img, 0,0, img.width, img.height-cutY, 0, 0, img.width*ratioX, (img.height-cutY)*ratioY);

It does not work correctly, look (click on the image): https://jsfiddle.net/1mL9qfmd/4/ (gif: http://wgrajo.pl/img/ezgif48510c879ec.gif)

I tried to add ratioX / ratioY to the position of the mouse, but it does not help. I used also PointerClick to control mouse position.

Any ideas?


Solution

  • Ok i solved it https://jsfiddle.net/1mL9qfmd/11/.

    html:

    <canvas id="game" width="640" height="480" style="position: absolute; left:0px; top:0px; border:1px red solid;"></canvas>
    

    javascript:

    var img = new Image;
    img.src = 'http://wowslider.com/sliders/demo-93/data1/images/sunset.jpg';
    var ctx = game.getContext('2d');
    var ratioX = 2700/2300;
    var ratioY = 1300/1080;
    var cutY = 70;
    var mouse = {y: 0, x: 0};
    var distance = 0;
    setInterval(function(){
       ctx.clearRect(0,0,game.width, game.height);                               
       ctx.drawImage(img, 0,0, img.width, (img.height-cutY)-distance/ratioY, 0, 0, img.width*ratioX, (img.height-cutY-distance/ratioY)*ratioY);
    },1000/60);
    
    window.addEventListener('mousemove', function(e){
       mouse.y = e.pageY;
       mouse.x = e.pageX;
    }, false);
    
    window.addEventListener('mousedown', function(e){
       distance = Math.abs(mouse.y-mouse.y*ratioY);
       cutY = img.height-(mouse.y);
    }, false);