html2canvas使用教程

一、需求

  1. 将页面某元素节点的内容转化为图片

  2. 将图片的blob文件流传给服务器(简而言之:拿到图片的File对象)

二、使用 html2canvas 案列

  1. 安装 html2canvas

npm install html2canvas
 or
yarn add html2canvas

  2. 使用

import html2canvas from 'html2canvas'

html2canvas(document.body).then(function(canvas) {
  document.body.appnedChild(canvas)
})

三、 实现需求

  1. 解析图片,导出blob文件流

    // 解析图片,导出blob文件流
    async captureElementAsFile () {
      // 元素节点
      const content = this.$refs.printContainer
      const canvas = await html2canvas(content, {
        allowTaint: true, // 是否允许不同源的图片污染画布 (允许绘制)
        useCORS: true, // 是否尝试使用 CORS 从服务器加载图片 (允许跨域)
        // logging: true, // 启用日志记录以进行调试
        width: content.clientWidth * 1.005, // 设置图片宽度
        height: content.clientHeight * 1.005 // 设置图片高度
      })
      // 转blob文件流
      const blob = await new Promise(resolve => {
        canvas.toBlob(resolve, 'image/png')
      })
      // blob文件流转File对象
      const file = new File([blob], 'element.png', { type: 'image/png' })
      // 转base64格式图片
      const base64 = canvas.toDataURL('image/png')
    },

  2. 下载图片

  方案一:

    async downloadImage () {
      const content = this.$refs.equipmentInfo
      const canvas = await html2canvas(content)
      const url = canvas.toDataURL('image/png')
      const filename = 'qrCode.png'
      const link = document.createElement('a')
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }

  方案二:

    async downloadImage () {
      const content = this.$refs.printContainer
      const canvas = await html2canvas(content, {
        allowTaint: true,
        useCORS: true,
        logging: true
      })
      const dataURL = canvas.toDataURL('image/png')
      console.log(dataURL, 'dataURL')
      const link = document.createElement('a')
      link.download = 'drawing.png'
      link.href = dataURL
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }

 四、使用html2canvas存在的问题

问题:
  1、如果将节点转为图片时,节点内容存在第三放文件资源时,
     可能会忽略编译第三方资源,亦或者会出现请求第三方文件跨域的问题。
  
  2、下载第三方资源图片可能会出现跨域问题


解决方法:给html2canvas进行配置,使用 allowTaint,useCors 属性
         同时需要配置你的第三方资源服务器,使服务器允许跨域


案列:鄙人的电放资源文件是图片,并且保存在阿里云的oss服务器上,(阿里云的oss服务器需要购买)
      你需要去 阿里云的oss服务器 配置允许跨域
 html2canvas中文文档:  https://allenchinese.github.io/html2canvas-docs-zh-cn/icon-default.png?t=N7T8https://allenchinese.github.io/html2canvas-docs-zh-cn/ 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值