npm install html2canvas
import html2canvas from 'html2canvas'
- 给一个元素渲染html2canvas 的操作
html2canvas(element, options);
// 需要截图的包裹的(原生的)DOM 对象
const shareContent = document.getElementById("shareContent");
// 获取dom 宽度
const width = shareContent.offsetWidth;
// 获取dom 高度
const height = shareContent.offsetHeight;
// 创建一个canvas节点
const canvas = document.createElement("canvas");
// 定义任意放大倍数 支持小数
const scale = 2;
// 定义canvas 宽度 * 缩放
canvas.width = width * scale;
// 定义canvas高度 *缩放
canvas.height = height * scale;
// 获取context,设置scale
canvas.getContext("2d").scale(scale, scale);
// 设置参数
objs = {
// 【重要】开启跨域配置
useCORS: true,
background: "#ffffff",
onrendered: function(canvas) {
canvas.setAttribute('id','thecanvas'); //添加属性
document.body.appendChild(canvas);
}
html2canvas(shareContent).then(canvas => {
document.body.appenChild(canvas)
// 引入canvas 生成的图片
const getImg = canvas.toDataURL('image/png')
})
canvas2image
保存canvas图片 web上使用
需要修改源码
var Canvas2Image = function () {}
// =>
module.exports = function () {}
// 引用
import 'canvas2image'
Canvas2Image.saveAsImage(canvasObj, width, height, type)
Canvas2Image.saveAsPNG(canvasObj, width, height)
Canvas2Image.saveAsJPEG(canvasObj, width, height)
Canvas2Image.saveAsGIF(canvasObj, width, height)
Canvas2Image.saveAsBMP(canvasObj, width, height)
Canvas2Image.convertToImage(canvasObj, width, height, type)
Canvas2Image.convertToPNG(canvasObj, width, height)
Canvas2Image.convertToJPEG(canvasObj, width, height)
Canvas2Image.convertToGIF(canvasObj, width, height)
Canvas2Image.convertToBMP(canvasObj, width, height)