前端截图html2canvas

11 阅读1分钟

前言

有时候前端可能会有给页面截图的需求,此时我们可以用比较常见的工具html2canvas,毕竟自己写的话也非常麻烦,一般人写不出来,下面就简单介绍下它吧

html2canvas 实际上就跟我们浏览器渲染html页面一样,他会先进行样式计算,然后开始布局,然后逐步绘制到canvas上,再把绘制好的canvas返回给我们就是了

同时它还处理了网络图片跨域等问题,可以说一步到位,自己写的花,光想就知道很麻烦了,这里就不多介绍了,直接看怎么使用

案例

导入 html2canvas

yarn add html2canvas

使用案例

import { useRef } from "react";
import html2canvas from "html2canvas";

function App() {
  const ref = useRef()
  
  return (
    <div className="App">
      <div ref={ref}>
        <h1>React Demo</h1>
        <h2>Welcome to the React demo application!</h2>
      </div>
      <div onClick={() => {
        //默认第二个参数option不用填写就行
        html2canvas(ref.current,  {
          //useCORS: true, // 解决跨域图片渲染问题,有网络图片可以考虑
          //scale: 2, // 提高分辨率,避免模糊
          //backgroundColor: '#ffffff', // 设置背景色(默认透明)
        }).then(canvas => {
          //直接下载图片
          const link = document.createElement('a');
          link.download = 'screenshot.png';
          link.href = canvas.toDataURL();
          link.click();
        });
      }}>点击</div>
    </div>
  );
}

export default App;