Take the 2-minute tour ×

I am trying to copy part of a fabricjs canvas to another canvas.I am not sure if fabric has a method suitable for doing it (please let me know if that's the case) and after some searching I decided to do it without using fabric. But the canvas was already created using fabricjs. new fabric.Canvas(). Now when I try to copy a part of this canvas using context.drawImage(), I get a TypeError. I tried replacing the canvas with a img or a canvas created without using fabric and that works. So, I am guessing I may have to use the fabric canvas object a bit differently.

share|improve this question
You can populate Fabric's canvas contents using JSON, SVG or object representation. This article explains this in detail. Similarly, you can load Fabric canvas using any of those formats. If you need to skip any of the objects from original canvas, just (temporarily?) remove them before export. –  kangax Feb 6 '13 at 23:42
Not exactly what I want. Sorry, when I read back my question I realized I was not clear enough. What I need to do is to basically crop the canvas itself (with objects drawn on it already, if any). So I was hoping I could copy the portion of the canvas I want to keep after crop with drawImage(), supplying the sx,sy,sh etc.. params and draw it on a new canvas. but when I set the source as fabric canvas, I get the error. –  redGREENblue Feb 7 '13 at 6:45
Well, you can do canvas.toDataURL(...) to get an image, but no way to specify cropping area. You can then position that image on a different canvas (possibly cropping it before). –  kangax Feb 7 '13 at 22:21
add comment

1 Answer

If you want to copy a rectangular zone from the canvas in order to export it as an image you could use the following:

      var ctx = canvas.getContext("2d");
      var myImageData = ctx.getImageData(box.x, box.y, box.w, box.h);
      var buffer = document.createElement('canvas');
      var bufferCtx = buffer.getContext("2d");
      buffer.width = box.w;
      buffer.height = box.h;
      bufferCtx.putImageData(myImageData, 0, 0);
share|improve this answer
add comment

Your Answer


