JavaScript 使用 html2canvas 生成图片

html2canvas 是一个 JavaScript 库,它允许你将 HTML 内容渲染为 Canvas 元素,进而可以导出为图片。这对于打印或者保存网页的快照非常有用。以下是如何使用 html2canvas 的基本步骤:

1. 安装 html2canvas

如果你正在使用模块化 JavaScript 或者构建工具(如 Webpack),你可以通过 npm 来安装 html2canvas:

npm install html2canvas

2. 导入 html2canvas

在你的 JavaScript 文件中导入 html2canvas:

import html2canvas from 'html2canvas';

如果你是在 <script> 标签中使用,可以直接加载 CDN 提供的版本,并且可以通过全局变量 html2canvas 访问:

<script src="https://cdn.jsdelivr.net/npm/html2canvas@latest/dist/html2canvas.min.js"></script>

3. 使用 html2canvas

使用 html2canvas() 方法来创建 canvas 的 HTML 快照。这是一个异步操作,通常需要通过 .then() 回调函数来处理结果。

html2canvas(document.body).then(function(canvas) {
    // 在这里处理生成的 canvas 对象
    document.body.appendChild(canvas);
});

选项

html2canvas 提供了很多选项来定制输出,例如:

  • scale - 设置渲染的缩放比例,默认为 2。
  • logging - 开启或关闭日志记录,默认为 false。
  • width 和 height - 设置 canvas 的宽度和高度。
  • dpiScaling - 设置 DPI 缩放。
  • useCORS - 是否使用跨源资源共享 (CORS) 来获取图像数据。
  • allowTaint - 允许污染 canvas 否则会启用 CORS。

示例

下面是一个完整的示例代码,展示了如何将某个特定的 HTML 元素转换为 canvas 并下载为图片文件:

document.getElementById('export').addEventListener('click', function() {
    var input = document.getElementById('content'); // 要转换的 HTML 元素
    html2canvas(input, {
        onrendered: function(canvas) {
            document.body.appendChild(canvas); // 可视化 canvas
            // 下载为图片文件
            var imgData = canvas.toDataURL("image/png");
            var dlLink = document.createElement('a');
            dlLink.href = imgData;
            dlLink.download = "screenshot.png";
            document.body.appendChild(dlLink);
            dlLink.click();
            document.body.removeChild(dlLink);
        }
    });
});

请确保阅读 html2canvas 的官方文档以了解所有可用的选项和功能,以及如何处理一些常见的问题,比如第三方资源加载失败等。官方文档通常是最权威的信息来源。

 

不支持图片 object:cover 的解决方法,修改代码:

CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image) {
    // if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
    //     var box = contentBox(container);
    //     var path = calculatePaddingBoxPath(curves);
    //     this.path(path);
    //     this.ctx.save();
    //     this.ctx.clip();
    //     this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, box.left, box.top, box.width, box.height);
    //     this.ctx.restore();
    // }
    // 以上是被注释的原代码,下面是新加内容
    if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
      var box = contentBox(container);
      var path = calculatePaddingBoxPath(curves);

      this.path(path);
      this.ctx.save();
      this.ctx.clip();

      let newWidth;
      let newHeight;
      let newX = box.left;
      let newY = box.top;

      if(container.intrinsicWidth / box.width < container.intrinsicHeight / box.height) {
        newWidth = box.width;
        newHeight = container.intrinsicHeight * (box.width / container.intrinsicWidth);
        newY = box.top + (box.height - newHeight) / 2;
      } else {
        newWidth = container.intrinsicWidth * (box.height / container.intrinsicHeight);
        newHeight = box.height;
        newX = box.left + (box.width - newWidth) / 2;
      }

      this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, newX, newY, newWidth, newHeight);
      this.ctx.restore();
    }
};

修改时间 2024-09-10

声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏
搜神记
777 文章
4 教程
8 项目
随机推荐
MySQL的外键总结
WordPress 调用自定义头像
Page Visibility API
JavaScript EventSource 服务器发送事件 Server-Sent Events(SSE)
Node.js stream 流
JavaScript 私有方法和私有属性
如何调整 iconfont 图标的位置和基线
JavaScript 类操作 classList