1、安装
npm install html2canvas
2、用法
import html2canvas from 'html2canvas';
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});
在vue中使用,转换成图片下载至本地
<div ref="imageDom"></div>
html2canvas(this.$refs.imageDom,
{
useCORS: true, //图片跨域,开启跨域配置
logging: false,//日志开关,便于查看html2canvas的内部执行流程
taintTest: true,//是否在渲染前测试图片
}).then(canvas => {
// 转成图片,生成图片地址
let imgUrl = canvas.toDataURL("image/png"); //可将 canvas 转为 base64 格式
let eleLink = document.createElement("a");
eleLink.href = imgUrl; // 转换后的图片地址
eleLink.download = "名称";
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
});
html2canvas基本参数数说明
参数说明 | 默认值 | 描述 |
allowTaint | false | Whether to allow cross-origin images to taint the canvas---是否允许跨原点图像污染画布 |
backgroundColor | #ffffff | Canvas background color, if none is specified in DOM. Set null for transparent--canvas的背景颜色,如果没有设定默认透明 |
canvas | null | Existing canvas element to use as a base for drawing on |
foreignObjectRendering | false | Whether to use ForeignObject rendering if the browser supports it 如果浏览器支持,是否使用ForeignObject渲染 |
foreignObjectRendering | 15000 | Timeout for loading an image (in milliseconds). Set to 加载图像超时(毫秒)。设置为0以禁用超时。 |
ignoreElements | (element) => false | Predicate function which removes the matching elements from the render. 用于从呈现中移除匹配元素 |
logging | true | Enable logging for debug purposes 启用日志 |
onclone | null | Callback function which is called when the Document has been cloned for rendering, can be used to modify the contents that will be rendered without affecting the original source document. 克隆文档时调用的回调函数可用于修改将呈现的内容,而不会影响原始源文档。 |
proxy | null | Url to the proxy which is to be used for loading cross-origin images. If left empty, cross-origin images won't be loaded. 要用于加载跨原点图像的代理的Url。如果留空,则不会加载跨原点图像。 |
removeContainer | true | Whether to cleanup the cloned DOM elements html2canvas creates temporarily 是否清理html2canvas临时创建的克隆DOM元素 |
scale | window.devicePixelRatio | The scale to use for rendering. Defaults to the browsers device pixel ratio. 用于渲染的比例。默认为浏览器设备像素比。 |
useCORS | false | Whether to attempt to load images from a server using CORS 是否尝试使用CORS从服务器加载图像 |
width | Element width | canvas的宽度 |
height | Element height | canva的高度 |
x | Element x-offset | 裁剪画布x坐标 |
y | Element y-offset | 裁剪画布y坐标 |
scrollX | Element scrollX | 渲染元素时要使用的x轴滚动位置(例如,如果元素使用位置:fixed) |
scrollY | Element scrollY | 渲染元素时要使用的y轴滚动位置(例如,如果元素使用位置:fixed) |
windowWidth | Window.innerWidth | 渲染元素时要使用的窗口宽度,这可能会影响媒体查询之类的内容 |
windowHeight | Window.innerHeight | 渲染元素时要使用的窗口高度,这可能会影响媒体查询等操作 |