记录一个将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)
}

Logo

前往低代码交流专区

更多推荐