html2canvas error: Uncaught Error: IndexSizeError: DOM Exception 1

ErisoHV picture ErisoHV · Mar 10, 2013 · Viewed 18.9k times · Source

I am using html2canvas to convert a div on a canvas. Like this:

<script src="js/libs/jquery-1.7.1.min.js"></script>
<script src="js/libs/jquery-ui-1.8.17.custom.min.js"></script>
<script src="js/html2canvas/html2canvas.js"></script>
...
<body id="body">
  <div id="demo">
    ...
  </div>
</body>
<script>
$('#demo').html2canvas({
onrendered: function( canvas ) {
  var img = canvas.toDataURL()
  window.open(img);
}
});
</script>

and I get this error: "Uncaught Error: IndexSizeError: DOM Exception 1" in html2canvas.js:

ctx.drawImage( canvas, bounds.left, bounds.top, bounds.width, bounds.height, 0, 0, bounds.width, bounds.height );

Does anyone has idea about's what happening?

Answer

Saturnix picture Saturnix · Mar 11, 2013

Whenever you call drawImage on a canvas and you want to crop an image, you have to pass in 9 values.

ctx.drawImage(
imageObject,
sourceX,
sourceY,
sourceWidth,
sourceHeight,
destX,
destY,
destWidth,
destHeight);

now that's a lot of stuff! It's really easy to make errors: to avoid them, let me explain how does drawImage works when cropping an image.

Imagine to draw a square on a piece of paper. The top-left corner of the square you're drawing is positioned at sourceX pixels and sourceY pixels where 0 is the top-left corner of your piece of paper. The dimension in pixels of the square you're drawing are defined by sourceWidth and sourceHeight.

Everything inside of the square you've defined, will now be cut and pasted inside of your canvas at the position (in pixels) destX and destY (where 0 is the top-left corner of your canvas).

Because we're not in real life, the square you cut may be stretched and have a different dimension. This is why you also have to define destWidth and destHeight

Here's a graphical representation of all this.

none

To get back to your question, Uncaught Error: IndexSizeError: DOM Exception 1 usually appears when the square you're trying to cut is bigger than the actual piece of paper, or you're trying to cut the piece of paper in a position where it doesn't exists (like sourceX = -1, which is impossible for obvious reasons).

I have no idea what bounds.left, bounds.top and the others are, but I'm 99.9% sure that they're wrong values. Try to console.log them and compare them with the image object you're providing (in this case, the canvas).

console.log(canvas.width);
console.log(canvas.height);
console.log(bounds.left);
console.log(bounds.top);
ecc....