html2canvas使用文档

一、安装

Install NPM

npm install --save html2canvas

Install Yarn

yarn add html2canvas

二、引入

import html2canvas from 'html2canvas';

三、使用

以 vue 举例,这样写起来比较方便

Hello world!

// 配置项
const setup = { useCORS: true, // 使用跨域
};
html2canvas(this.$refs.picture, setup).then((canvas) => { document.body.appendChild(canvas); // 自动在下方显示绘制的canvas图片
});

如果想要将图片导出,可以这样写

// 生成图片
creatImg() { const setup = { useCORS: true, // 使用跨域
    };
    html2canvas(this.$refs.picture, setup).then((canvas) => { const link = canvas.toDataURL("image/jpg");
        this.exportPicture(link, "文件名");
    });
}
// 导出图片
exportPicture(link, name = "未命名文件") { const file = document.createElement("a");
    file.style.display = "none";
    file.href = link;
    file.download = decodeURI(name);
    document.body.appendChild(file);
    file.click();
    document.body.removeChild(file);
}

四、配置项

名称默认值描述
allowTaintfalse是否允许跨源图像污染画布
backgroundColor#ffffff画布背景色(如果在DOM中未指定),为透明设置null
canvasnull用作绘图基础的现有画布元素
foreignObjectRenderingfalse如果浏览器支持ForeignObject渲染,是否使用它
imageTimeout15000加载图像超时(毫秒),设置为0可禁用超时
loggingtrue为调试目的启用日志记录
proxynull用于加载跨源图像的代理的Url。如果留空,则不会加载跨原点图像。
removeContainertrue是否清除html2canvas临时创建的克隆DOM元素
scalewindow.devicePixelRatio用于渲染的比例。默认为浏览器设备像素比率。
useCORSfalse是否尝试使用CORS从服务器加载图像
widthElement width画布的宽度
heightElement height画布的高度
xElement x-offset裁剪画布x坐标
yElement y-offset裁剪画布y坐标
scrollXElement scrollX渲染元素时要使用的x滚动位置(例如,如果元素使用位置:fixed)
scrollYElement scrollY渲染元素时要使用的y轴滚动位置(例如,如果元素使用位置:fixed)
windowWidthWindow.innerWidth渲染Element时使用的窗口宽度,这可能会影响Media查询等内容
windowHeightWindow.innerHeight渲染Element时使用的窗口高度,这可能会影响Media查询等内容

大部分情况下使用默认配置即可,如有需要,可根据配置项修改。