0

I have an image (imgt) and a resizable and movable crop div (ram) and want to crop imgt according to size and position of ram.

Result - dimensions are ok, but there is no image, just a black rectangle.

var img = document.getElementById("imgt");
c1 = document.createElement("canvas");
var ctx = c1.getContext("2d");

var a = $('#imgt').width();
var b = $('#imgt').height();
c1.width = a;
c1.height = b;
ctx.drawImage(img, 0, 0, a, b);

ax = $('#ram').position().left;
ay = $('#ram').position().top;
aw = $('#ram').width();
ah = $('#ram').height();

var img = new Image();
img.src = c1.toDataURL('image/jpeg');
c2 = document.createElement("canvas");
c2.width = aw;
c2.height = ah;

var ctx = c2.getContext("2d");
ctx.drawImage(img, ax, ay, aw, ah, 0, 0, aw, ah);

var dl = document.createElement("a");
dl.href = c2.toDataURL("image/jpeg");
dl.download = true;
document.body.appendChild(dl);
dl.click();
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • Your `var ctx` is defined twice - could this be the issue? – Anis R. Apr 20 '19 at 05:13
  • @AnisR., no, they are for different canvas. I tried to change but the same result. – qadenza Apr 20 '19 at 05:17
  • 1
    What is the result of `console.log(c1.toDataURL('image/jpeg'))`? I suspect that your `src` is wrong or invalid, and hence the black rect – Samleo Apr 20 '19 at 05:23
  • @Samleo, result - `data:image/jpeg;base64,...` – qadenza Apr 20 '19 at 05:26
  • Is your canvas's background transparent? If so, then converting to PNG instead of JPEG in `toDataURL()` should fix it. See https://stackoverflow.com/questions/26742180/canvas-todataurl-results-in-solid-black-image – Anis R. Apr 20 '19 at 05:35
  • @AnisR., doesn't help anything – qadenza Apr 20 '19 at 05:47
  • 1. You may consider using `img.onload = function() {ctx.drawImage(...` 2. I would need to know the size of your image because you may draw the image outside the canvas: `ctx.drawImage(img, ax, ay, aw, ah, 0, 0, aw, ah);`. 3. You should avoid using `ctx` twice. why not using `ctx2` the second time? And the same for the image. A nice way to debug your code would be appending the canvases to the DOM to see what happens. – enxaneta Apr 20 '19 at 15:39

0 Answers0