在vue中使用html2canvas在前端生成图片

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基本参数数说明

参数说明默认值描述
allowTaintfalseWhether to allow cross-origin images to taint the canvas---是否允许跨原点图像污染画布
backgroundColor#ffffffCanvas background color, if none is specified in DOM. Set null for transparent--canvas的背景颜色,如果没有设定默认透明
canvasnullExisting canvas element to use as a base for drawing on
foreignObjectRenderingfalse

Whether to use ForeignObject rendering if the browser supports it

如果浏览器支持,是否使用ForeignObject渲染

foreignObjectRendering15000

Timeout for loading an image (in milliseconds). Set to 0 to disable timeout.

加载图像超时(毫秒)。设置为0以禁用超时。

ignoreElements(element) => false

Predicate function which removes the matching elements from the render.

用于从呈现中移除匹配元素

loggingtrue

Enable logging for debug purposes

启用日志

onclonenull

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.

克隆文档时调用的回调函数可用于修改将呈现的内容,而不会影响原始源文档。

proxynull

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。如果留空,则不会加载跨原点图像。

removeContainertrue

Whether to cleanup the cloned DOM elements html2canvas creates temporarily

是否清理html2canvas临时创建的克隆DOM元素

scalewindow.devicePixelRatio

The scale to use for rendering. Defaults to the browsers device pixel ratio.

用于渲染的比例。默认为浏览器设备像素比。

useCORSfalse

Whether to attempt to load images from a server using CORS

是否尝试使用CORS从服务器加载图像

widthElement widthcanvas的宽度
heightElement heightcanva的高度
xElement x-offset裁剪画布x坐标
yElement y-offset裁剪画布y坐标
scrollXElement scrollX渲染元素时要使用的x轴滚动位置(例如,如果元素使用位置:fixed)
scrollYElement scrollY渲染元素时要使用的y轴滚动位置(例如,如果元素使用位置:fixed)
windowWidthWindow.innerWidth渲染元素时要使用的窗口宽度,这可能会影响媒体查询之类的内容
windowHeightWindow.innerHeight渲染元素时要使用的窗口高度,这可能会影响媒体查询等操作

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值