0

I have a canvas of size 300px to 300px and I drag and drop a very large image on to it. so it takes the size of the canvas. Then I have a resizable and moveable square which I use to crop certain areas. So using jquery I take the width and height of the crop square and the x and y distance to the clipping point. But when I finally crop and display the region in a second canvas I can see that the cropped region is not exactly what I selected as the region to be cropped.

I dont want to use getimagedata and putimagedata commands. I want to use drawimage command only

Please help

var x = $("#crop_square").width();
var y = $("#crop_square").height();

var ty = $("#crop_square").offset().top - $("#area_c").offset().top;
var tx = $("#crop_square").offset().left - $("#area_c").offset().left;


var c =  document.getElementById("area_c");
var c2 =  document.getElementById("area_c2");

var ctx = c.getContext("2d");
var ctx2 = c2.getContext("2d");

ctx2.drawImage(image_src,tx,ty,x, y,0,0,c2.width,c2.height);




 <canvas id ="area_c" style="width:300px;height:300px;border:3px solid black;z-index:1"  ondrop="dropb(event)"  ondragover="myfkb(event)"   >
 </canvas>

 <canvas  id ="area_c2" style="width:300px;height:300px;border:3px solid black;z-index:1"  >

  </canvas>
Mia Davis
  • 131
  • 9
  • 1
    Possible duplicate of [Crop an image displayed in a Canvas](https://stackoverflow.com/questions/28538913/crop-an-image-displayed-in-a-canvas) – Vishnudev Krishnadas Jun 15 '19 at 07:30
  • It is not. i referred that stack overflow question. It uses getImagedata . I dont want to use that. I simply want to use draw image command only . Also my problem here is that crop square dimensions dont match with the cropped area – Mia Davis Jun 15 '19 at 07:47
  • Instead of `ctx2.drawImage(image_src,tx,ty,x, y,0,0,c2.width,c2.height);` try using `ctx2.drawImage(c,tx,ty,x, y,0,0,c2.width,c2.height);`. – enxaneta Jun 15 '19 at 07:49
  • I think the problem is crop square dimensions don't match with the image because of its compressed size – Mia Davis Jun 15 '19 at 07:55
  • It is very much likely that `offset()` doesn't return what you expect due to DOM element nesting you have. You should create a fiddle and demonstrate your problem. – Charlie Jun 15 '19 at 08:03
  • You need to edit your question to include a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – Herohtar Jun 15 '19 at 08:06

1 Answers1

0

Don't minus area_c top and left from tx,ty Try this

var x = $("#crop_square").width();
var y = $("#crop_square").height();

var ty = $("#crop_square").offset().top;
var tx = $("#crop_square").offset().left;


var c =  document.getElementById("area_c");
var c2 =  document.getElementById("area_c2");

var ctx = c.getContext("2d");
var ctx2 = c2.getContext("2d");

ctx2.drawImage(image_src,tx,ty,x, y,0,0,c2.width,c2.height);

enxaneta
  • 31,608
  • 5
  • 29
  • 42
kishan vekariya
  • 431
  • 3
  • 11