使用html2canvas將html通過canvas轉換成圖片


  html2canvas官網: http://html2canvas.hertzen.com/documentation

一、html2canvas的兼容性

  根據官網給出的API,html2canvas的兼容性如下

  1、Firefox 3.5+

  2、Google Chrome

  3、Opera 12+

  4、IE9+

  5、Edge

  6、Safari 6+

二、下載使用html2canvas插件  

  1、通過npm安裝html2canvas

npm install html2canvas

  2、在項目中通過import引入

import html2canvas from 'html2canvas'

三、html2canvas的常用的可用參數

參數名稱 類型 默認值 描述
allowTaint boolean false 是否允許跨域圖像污染畫布
backgroundColor string #fff canvas的背景顏色,如果沒有設定默認透明,也可以使用rgba
width number null canvas畫布的寬度
height number null canvas畫布的高度
proxy string null 代理地址
useCORS boolean false 是否嘗試使用CORS從服務器加載圖像
scale number 1 縮放比例,默認為1

 

四、基本語法

html2canvas(element,options).then((canvas) =>{})

  element:所需要截圖的元素,doucument.getElementById獲取

  options:配置的參數

  cavans:截圖后返回的最后一個cavans

五、html2canvas的使用

import React from 'react';
import { Button } from 'antd';
import html2canvas from 'html2canvas'
export default () => {
  const canvasImg = () => {
    let canvasEle: any = document.getElementById('html2canvasTest')  //獲取元素
    html2canvas(canvasEle, {
      width: 200, //設置canvas的寬度
      scale: 2,//縮放
    }).then((canvas) => {
      //處理你生成的canvas
      // document.body.appendChild(canvas);
      let a = document.createElement('a');
      a.setAttribute('href', canvas.toDataURL());  //toDataUrl:將canvas畫布信息轉化為base64格式圖片
      a.setAttribute('download', 'downImg')  //這個是必須的,否則會報錯
      a.setAttribute('target', '_self');
      a.click()
    })
  }
  return (
    <div >
      <div id="html2canvasTest">
        <p style={{ color: 'red', background: '#f5f5f5', padding: '20px', border: '1px solid red', width: '200px' }}>
          html2canvas將html通過canvas轉換成圖片
      </p>
      </div>
      <Button onClick={canvasImg}>點擊生成圖片並下載</Button>
    </div>
  );
}

  注意:如果a標簽沒有添加download屬性,那點擊按鈕下載圖片時,谷歌瀏覽器就會報錯

  點擊下載按鈕后,下載成功:

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM