html2canvas官网:
GitHub:
使用html2canvas
安装依赖:
yarn add html2canvas
在Vue中的使用示例:
<template>
<div class="canvas-app">
<!-- canvas原内容 -->
<div class="canvas-content">
<div class="canvas-content-text">这是文本内容</div>
</div>
<!-- 按钮 -->
<div class="canvas-btns">
<div @click="generatorCanvas">生成海报</div>
</div>
<!-- canvas生成弹窗 -->
<div class="canvas-wrap">
<div class="canvas-wrap-img">
<img :src="imgUrl" alt="">
</div>
<div class="canvas-wrap-content"></div>
</div>
</div>
</template>
<script>
import html2canvas from 'html2canvas';
export default {
data() {
return {
imgUrl: ''
}
},
methods: {
generatorCanvas() {
let ele = document.querySelector('.canvas-content')
html2canvas(ele, {
backgroundColor: "#ffffff",
allowTaint: true, //开启跨域
useCORS: true,
scrollY: 0,
scrollX: 0,
}).then(canvas => {
let wrap = document.querySelector('.canvas-wrap-content')
wrap.appendChild(canvas);
this.imgUrl = canvas.toDataURL('image/png');
// debugger
});
}
}
};
</script>
<style>
.canvas-content {
height: 50px;
background-color: #0f0;
}
.canvas-content-text {
color: red;
}
</style>
生成后的DOM结构:
图片跨域问题
如果是同源的图片路径,像这种,生成海报图片是正常的:
<div class="canvas-content">
<div class="canvas-content-text">这是文本内容</div>
<div>
<img src="/favicon.png" width="100" height="100" alt="">
</div>
</div>
如果是非同源的图片路径,生成海报将报错:
<div class="canvas-content">
<div class="canvas-content-text">这是文本内容</div>
<div>
<img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="">
</div>
</div>
点击“生成海报”报跨域问题:
解决方案有两种,都需要服务端支持。
方法一:服务器设置静态资源响应头 Access-Control-Allow-Origin
为 *
或者域名白名单,然后在img标签添加crossorigin="anonymous"
属性。
<img crossorigin=“anonymous” src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="">
方法二:使用代理服务器获取资源。参考: