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.
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....
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…