jquery - html2canvas错误: Uncaught Error: IndexSizeError: DOM Exception 1

标签 jquery canvas html2canvas

我正在使用 html2canvas 转换 Canvas 上的 div。像这样:

<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>

我收到此错误:“未捕获错误:IndexSizeError:DOM 异常 1” 在 html2canvas.js 中:

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

有人知道发生了什么吗?

最佳答案

每当您在 Canvas 上调用 drawImage 并想要裁剪图像时,都必须传入 9 个值。

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

现在有很多东西了!很容易犯错误:为了避免错误,让我解释一下drawImage在裁剪图像时是如何工作的。

想象一下在一张纸上画一个正方形。您正在绘制的正方形的左上角位于 sourceX 像素和 sourceY 像素处,其中 0 是纸张的左上角。您所绘制的正方形的尺寸(以像素为单位)由 sourceWidthsourceHeight 定义。

您定义的正方形内的所有内容现在都将被剪切并粘贴到 Canvas 内的 destXdestY 位置(以像素为单位)(其中 0是 Canvas 的左上角)。

因为我们不在现实生活中,所以您切割的正方形可能会被拉伸(stretch)并具有不同的尺寸。这就是为什么您还必须定义 destWidthdestHeight

这是所有这一切的图形表示。

none

回到你的问题,Uncaught Error: IndexSizeError: DOM Exception 1 通常在你尝试剪切的正方形比实际的纸张大或者你正在尝试时出现将这张纸剪到不存在的位置(例如 sourceX = -1,由于显而易见的原因,这是不可能的)。

我不知道 bounds.leftbounds.top 和其他值是什么,但我 99.9% 确信它们是错误的值。尝试console.log它们并将它们与您提供的图像对象(在本例中为 Canvas )进行比较。

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

关于jquery - html2canvas错误: Uncaught Error: IndexSizeError: DOM Exception 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15328764/

相关文章:

javascript - 更改 contenteditable div 中文本的颜色

javascript - Phonegap onDeviceOnline

css - 在 html Canvas 圆圈中有多个可点击的部分,在每个被点击的区域填充颜色

javascript - 每个内的 jQuery 仅将函数绑定(bind)到最终项目

javascript - 如何使用单击事件处理程序在点之间画线?

javascript - 如何自动下载从 Canvas 元素获取的图像?

jspdf - Html2Canvas 未在 iOS 中渲染 Font Awesome 图标

javascript - html2canvas 基础知识

javascript - 使用 React 生成动态 PDF

javascript - 获取被单击元素的属性值