使用html2Canvas插件实现页面部分区域截屏效果

使用html2Canvas插件实现页面部分区域截屏效果

一、场景和需求

最近在做的项目有这样一个需求:APP的打卡分享到微信好友和微信朋友圈的功能。实质就是将网页内容生成一张图片给分享出去(不是抛出一个网页链接啥的),那么问题来了,如何将网页上的某一块内容转换为图片呢?

二、解决方案

使用html2canvas插件来实现。html2canvas是一款利用javascript进行屏幕截图的插件,它能够实现在用户浏览器端直接对整个或部分页面进行截屏。

三、前期准备

1.安装 html2canvas

npm install html2canvas --save  或 yarn add html2canvas

 
 
   
   
   
   
  • 1

2.引入 html2canvas

import html2canvas from "html2canvas";

 
 
   
   
   
   
  • 1

四、具体实现小demo

<template>
  <div id="page">
    <!-- 截图区域 -->
    <div class="content" ref="content">这里是丰富的网页内容...</div>
    <!-- 点击调用方法获取截图 -->
    <button class="btn" @click="getPrintScreen">获取截图</button>
    <div class="img-box">
      <h2>截图结果:</h2>
      <!-- 通过img标签把获取到的截图呈现出来 -->
      <img :src="imgUrl" alt="" />
    </div>
  </div>
</template>
<script>
// 引入 html2canvas
import html2canvas from “html2canvas”;
export default {
name: “Screenshot”,
data() {
return {
imgUrl: null, //截图地址
};
},
methods: {
	//获取截图方法
	getPrintScreen() {
		// 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
		html2canvas(this.$refs.content, {
				// width: 30, //截图宽度
				// height: 50, //截图高度
				backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色(null)
				useCORS: true, //支持图片跨域
				scale: 1, //设置放大的倍数
			}).then((canvas) => {
				// 把生成的base64位图片上传到服务器,生成在线图片地址
				let url = canvas.toDataURL(“image/png”); // toDataURL: 图片格式转成 base64
				this.imgUrl = url;
			});
		},
	},
};
</script>

你可能感兴趣的:(前端,javascript,前端,开发语言)