1

I use a canvas for cropping a jpg, i wish use this cropped img in another canvas

/**************CANVAS cropping img *********/

  var canvas1 = document.getElementById('Canvas1');
  var context1 = canvas1.getContext('2d');
  var imageObj = new Image();

  imageObj.onload = function() {
    // draw cropped image
    var sourceX = 90;
    var sourceY = 0;
    var sourceWidth = 319;
    var sourceHeight = 319;
    var destWidth = sourceWidth;
    var destHeight = sourceHeight;
    var destX = canvas1.width / 2 - destWidth / 2;
    var destY = canvas1.height / 2 - destHeight / 2;

    context1.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
  };
  imageObj.src = 'OriginImg.jpg';

/**************CANVAS using cropping img *********/

  var canvas2 = document.getElementById('Canvas2');
  var context2 = canvas2.getContext('2d');
  var img = new Image();
  img.src = canvas1;
  context2.drawImage(img, 10,10);
gurrumo
  • 83
  • 2
  • 10

1 Answers1

1

This isn't the standard way of drawing a canvas onto another one, and is discouraged, but if you want to use this method, you can always turn the first canvas into it's dataURL and use that as the src:

img.src = canvas1.toDataURL() will work just fine for you.

Check out the mdn page for .toDataURL().

The standard method would be to simply draw one of the canvases on the other:

ctx2.drawImage( canvas1, 0, 0 )

More information can be found in the mdn page for .drawImage()

towc
  • 1,983
  • 2
  • 22
  • 36