将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>
  );
};
相关推荐
于慨1 天前
Lambda 表达式、方法引用(Method Reference)语法
java·前端·servlet
石小石Orz1 天前
油猴脚本实现生产环境加载本地qiankun子应用
前端·架构
从前慢丶1 天前
前端交互规范(Web 端)
前端
CHU7290351 天前
便捷约玩,沉浸推理:线上剧本杀APP功能版块设计详解
前端·小程序
GISer_Jing1 天前
Page-agent MCP结构
前端·人工智能
王霸天1 天前
💥别再抄网上的Scale缩放代码了!50行源码教你写一个永不翻车的大屏适配
前端·vue.js·数据可视化
小领航1 天前
用 Three.js + Vue 3 打造炫酷的 3D 行政地图可视化组件
前端·github
@大迁世界1 天前
2026年React大洗牌:React Hooks 将迎来重大升级
前端·javascript·react.js·前端框架·ecmascript
PieroPc1 天前
一个功能强大的 Web 端标签设计和打印工具,支持服务器端直接打印到局域网打印机。Fastapi + html
前端·html·fastapi
悟空瞎说1 天前
深入 Vue3 响应式:为什么有的要加.value,有的不用?从设计到源码彻底讲透
前端·vue.js