meltingice / CamanJS

Javascript HTML5 (Ca)nvas (Man)ipulation
http://camanjs.com
BSD 3-Clause "New" or "Revised" License
3.56k stars 406 forks source link

X, Y position of Crop on some devices is wrong #205

Open tomaszs opened 8 years ago

tomaszs commented 8 years ago

I've created a demo. Canvas takes care of cropping properly, and CamanJS not. I noticed on my PC it works fine, but on my laptop not. So it can depend on screen resolutions. Also the issue is visible only in Firefox

http://polishwords.com.pl//dev/croperrortest.php

mejuliver commented 5 years ago

did you find a solution for this? can you share please? @tomaszs

tomaszs commented 5 years ago

Hello mejuliver. It was internal project where i used it. Eventually i just used computer on what it worked fine. So really didn't find a software solution. There seems to be a serious bug in CamanJS. I think also it is very hard to reproduce. No one here took this report. Maybe with more details they will be able.

mejuliver commented 5 years ago

@tomaszs hello, I sorted it out, it happens because Caman took the original dimension of the image as reference when cropping so the only solution is to resize the image so when cropping, it will get the correct area of the image. What I did, is just, I made the original image fit unto the responsive canvas, and it works great.

tomaszs commented 5 years ago

Cool. Can you provide any snippet for this? Maybe more people struggle

mejuliver commented 5 years ago

You can just bind the canvas on load function to the function below drawImageScaled

img.onload = drawImageScaled.bind(null, img, ctx);

function drawImageScaled(img, ctx) {
   ctx.canvas.width = img.offsetWidth;
   ctx.canvas.height = img.offsetHeight;

   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width;
   var vRatio =  canvas.height / img.height;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  

   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);

}

the function above will make the image fit inside with the given height and width. That's what I used on my image editor project https://github.com/mejuliver/image-editor