将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>
  );
};
相关推荐
未来之窗软件服务7 分钟前
幽冥大陆(八十八 ) 操作系统应用封装技术C#自解压 —东方仙盟练气期
java·前端·c#·软件打包·仙盟创梦ide·东方仙盟·阿雪技术观
沛沛rh451 小时前
React 学习笔记:State、hook —— 组件的记忆
前端·javascript·react.js
0和1的舞者9 小时前
Spring AOP详解(一)
java·开发语言·前端·spring·aop·面向切面
web小白成长日记9 小时前
在Vue样式中使用JavaScript 变量(CSS 变量注入)
前端·javascript·css·vue.js
QT 小鲜肉9 小时前
【Linux命令大全】001.文件管理之which命令(实操篇)
linux·运维·服务器·前端·chrome·笔记
C_心欲无痕9 小时前
react - useImperativeHandle让子组件“暴露方法”给父组件调用
前端·javascript·react.js
BullSmall11 小时前
支持离线配置修改及删除操作的实现方案
前端
全栈前端老曹12 小时前
【前端路由】Vue Router 嵌套路由 - 配置父子级路由、命名视图、动态路径匹配
前端·javascript·vue.js·node.js·ecmascript·vue-router·前端路由
EndingCoder12 小时前
安装和设置 TypeScript 开发环境
前端·javascript·typescript
张雨zy12 小时前
Vue 项目管理数据时,Cookie、Pinia 和 LocalStorage 三种常见的工具的选择
前端·javascript·vue.js