将html转化成图片

如何将指定html内容转化成图片保存?这个问题很值得深思,实际应用中也很有价值。最直接的想法就是使用canvas,熟悉canvas的同学可以尝试一下。这里不做太多的说明,本文采用html2canvas库来实现。

html2canvas库的使用非常简单,只需要引入html2canvas库,然后调用html2canvas方法即可,官方地址

接下来说一下简单的使用,以react项目为例。

获取整个页面截图,可以使用底层IDroot,这样下载的就是root下的所有元素。

js 复制代码
import html2canvas from "html2canvas";

const saveCanvas = () => {
    // 画布基础元素,要绘制的元素
    const canvas: any = document.getElementById("root");
    const options: any = { scale: 1, useCORS: true };
    html2canvas(canvas, options).then((canvas) => {
      const type = "png";
      // 返回值是一个数据url,是base64组成的图片的源数据
      let imgDt = canvas.toDataURL(type);
      let fileName = "img" + "." + type;
      // 保存为文件
      let a = document.createElement("a");
      document.body.appendChild(a);
      a.href = imgDt;
      a.download = fileName;
      a.click();
    });
  };

图片的默认背景色是#ffffff,如果想要透明色可设置为null,比如设置为红色。

js 复制代码
const options: any = { scale: 1, useCORS: true, backgroundColor: "red" };

正常情况下网络图片是无法渲染的,可以使用useCORS属性,设置为true即可。

js 复制代码
const options: any = { scale: 1, useCORS: true };

保存某块元素的截图

js 复制代码
const canvas: any = document.getElementById("swiper");

如果希望将某些元素排除,可以将data-html2canvas-ignore属性添加到这些元素中,html2canvas将从渲染中排除这些元素。

html 复制代码
<Button
  data-html2canvas-ignore
  color="primary"
  fill="solid"
  onClick={saveCanvas}
>
  download
</Button>

完整代码

js 复制代码
npm install html2canvas
css 复制代码
// demo.less
.contentSwiper {
  width: 710px;
  height: 375px;
  color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 48px;
  user-select: none;
}
.swiper {
  padding: 0 20px;
}
js 复制代码
import React from "react";
import { Button, Space, Swiper } from "antd-mobile";
import html2canvas from "html2canvas";
import styles from "./demo.less";

export default () => {
  const saveCanvas = () => {
    // 画布基础元素,要绘制的元素
    const canvas: any = document.getElementById("root");
    const options: any = { scale: 1, useCORS: true, backgroundColor: "red"
  };
    html2canvas(canvas, options).then((canvas) => {
      const type = "png";
      // 返回值是一个数据url,是base64组成的图片的源数据
      let imgDt = canvas.toDataURL(type);
      let fileName = "img" + "." + type;
      // 保存为文件
      let a = document.createElement("a");
      document.body.appendChild(a);
      a.href = imgDt;
      a.download = fileName;
      a.click();
    });
  };
  const colors: string[] = ["#ace0ff", "#bcffbd", "#e4fabd", "#ffcfac"];
  const items = colors.map((color, index) => (
    <Swiper.Item key={index}>
      <div className={styles.contentSwiper} style={{ background: color }}>
        {index + 1}
      </div>
    </Swiper.Item>
  ));
  return (
    <div className="content">
      <div id="swiper" className={styles.swiper}>
        <Swiper
          style={{
            "--track-padding": " 0 0 16px",
          }}
          defaultIndex={1}
        >
          {items}
        </Swiper>
      </div>
      <div>
        <img
          width={200}
          src="https://t7.baidu.com/it/u=2621658848,3952322712&fm=193&f=GIF"
        />
      </div>
      <Space>
        <Button
          data-html2canvas-ignore
          color="primary"
          fill="solid"
          onClick={saveCanvas}
        >
          download
        </Button>
        <Button color="primary" fill="solid">
          Solid
        </Button>
        <Button color="primary" fill="outline">
          Outline
        </Button>
        <Button color="primary" fill="none">
          None
        </Button>
      </Space>
    </div>
  );
};
相关推荐
子兮曰3 小时前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭4 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路6 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒7 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
Kagol8 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉8 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau8 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生8 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼8 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范
明君879978 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter