vue使用html2canvas将div内容转图片

记录一个将div内容转成图片的方法,获取到base64编码后,可以根据业务情况再处理

1、安装html2canvas

npm install html2canvas

2、引入安装的包

import html2canvas from "html2canvas"

3、将div内容添加上id属性

id="imgDiv"

4、点击保存按钮时,实现div转成base64的图片

const save = () => {
  var getPixelRatio = function (context) { // 获取设备的PixelRatio
    var backingStore = context.backingStorePixelRatio ||
        context.webkitBackingStorePixelRatio ||
        context.mozBackingStorePixelRatio ||
        context.msBackingStorePixelRatio ||
        context.oBackingStorePixelRatio ||
        context.backingStorePixelRatio || 0.5
    return (window.devicePixelRatio || 0.5) / backingStore
  }
  // 生成的图片名称
  var imgName = 'cs.jpg'
  //获取div的id
  var shareContent = document.getElementById('imgDiv')
  var width = shareContent.offsetWidth
  var height = shareContent.offsetHeight
  var canvas = document.createElement('canvas')
  var context = canvas.getContext('2d')
  var scale = getPixelRatio(context) // 将canvas的容器扩大PixelRatio倍,再将画布缩放,将图像放大PixelRatio倍。
  canvas.width = width * scale
  canvas.height = height * scale
  canvas.style.width = width + 'px'
  canvas.style.height = height + 'px'
  context.scale(scale, scale)

  var opts = {
    scale: 1,
    canvas: canvas,
    dpi: window.devicePixelRatio,
    // 获取元素宽高 让其以一个规律或者固定宽高伸展
    width: shareContent + 400,
    height: shareContent + 500,
    // 将截图部分 移入中心位置
    scrollX: 200,
    scrollY: 250
  }
  // 解决图片超出显示区后底色变成黑色的问题
  context.fillStyle = '#fff'

  context.fillRect(0, 0, canvas.width, canvas.height)
  var dataUrl = html2canvas(shareContent, opts).then(function (canvas) {
    context.imageSmoothingEnabled = false
    context.webkitImageSmoothingEnabled = false
    context.msImageSmoothingEnabled = false
    context.imageSmoothingEnabled = false
    return canvas.toDataURL('image/jpeg', 1.0)
  })
  console.log(dataUrl)
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值