使用html2canvas生成海报信息的详细文章及属性解释
效果图展示
一、安装与引入
首先,你需要在你的项目中安装html2canvas
。
npm install html2canvas
然后,在你的JavaScript文件中引入它:(也可以通过<script>
标签在HTML中引入官方GitHub仓库或CDN最新的链接。)
import html2canvas from 'html2canvas';
二、基本使用
主要方法:html2canvas(element[, options])
element
: 要转换为 canvas 的 HTML 元素。options
: 一个可选的对象,用于配置html2canvas
的行为。-
常见的
options
属性:
logging
(boolean): 默认为false
。如果设置为true
,将启用日志记录。useCORS
(boolean): 默认为false
。如果设置为true
,并且尝试加载跨域图像,那么html2canvas
将尝试使用 CORS 来加载图像。proxy
(string): 用于加载跨域图像的代理 URL。当使用 CORS 但图像没有正确的 CORS 标头时,可以使用此选项。backgroundColor
(string): 设置画布的背景色。默认为null
(透明)。scale
(number): 渲染时的缩放比例。默认为window.devicePixelRatio
。width
和height
(number): 指定输出的宽度和高度(以像素为单位)。如果不指定,则使用元素的 CSS 宽度和高度。ignoreElements
(function): 一个函数,用于确定哪些元素应被忽略。该函数应返回一个布尔值。allowTaint
(boolean): 默认为false
。如果设置为true
,则允许跨域图像污染画布(可能导致安全问题)。foreignObjectRendering
(boolean): 默认为false
。如果设置为true
,则尝试使用浏览器的内置支持来渲染 SVG 和 MathML。onclone
(function): 当元素被克隆到临时 DOM 以进行渲染时,此函数将被调用。onrendered
(function): 当canvas
被渲染并准备好转换为图像时,此函数将被调用。此函数接收一个参数,即渲染后的canvas
元素。
使用示例:
使用html2canvas
的基本步骤非常简单
首先,定义dom元素(targetDiv)
<div
id="target-element"
:style="{ background: posterInfo.bgColor }"
ref="targetDiv"
>
//页面编辑内容
</div>
然后,确保dom元素更新后,调用HTML2canvas,生成的canvas转换成图片。
//dom元素
const targetDiv = this.$refs.targetDiv;
await this.$nextTick();
// 获取dom元素宽高
const canvas = await html2canvas(targetDiv, {
//要生成的图片宽高
//height: targetDiv.offsetHeight,
height: targetDiv.scrollHeight - 1, //canvas高, 高度减 1 是为了解决底部出现白线问题
width: targetDiv.offsetWidth,
// 图片质量
scale: 2, //按比例增加分辨率 (2=双倍).
useCORS: true, // 启用 CORS 支持
allowTaint: true, // 允许图片被污染(即图片有跨域问题)
});
//调用canvas的toDataURL方法,生成base64图片
const imgData = canvas.toDataURL("image/png");
//将base64转换为图片文件
const file = this.dataUrlToFile(imgData, this.posterName);
dataUrlToFile方法:
dataUrlToFile(imgUrl, fileName) {
let arr = imgUrl.split(",");
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = window.atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], `${fileName}`, { type: mime });
},
最后,调用后端接口,实现上传图片,方便客户进行预览和下载分享。。