js常用插件之html2canvas截图生成海报
先引用cdn或自己下载下来
<script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
使用方法:
<body>
<button onclick="createPoster()">生成海报</button>
<!-- 海报样式 -->
<div class="poster-container" style="display: inline-block;">
</div>
<!-- 最终生成的海报图片 -->
<img id="posterImg" style="width: 400p;height: 700px;" />
</body>
// 生成海报
function createPoster() {
$('html,body').scrollTop('0px');
var dom = $('.poster-container')
html2canvas(dom[0], {
useCORS: true, //跨域
allowTaint: false,
logging: false,
letterRendering: true,
taintTest: true, //在渲染前测试图片
dpi: window.devicePixelRatio, // window.devicePixelRatio是设备像素比
background: "#fff"
}).then(function(canvas) {
var imgUrl = canvas.toDataURL('image/png');
document.getElementById('posterImg').setAttribute('src', imgUrl);
})
}
最后说一下如果海报里面的图片使用cdn产生跨域问题的解决方法
- 添加useCORS:true属性;
- 给要生成canvas的DOM中包含的每一个标签添加crossorigin="anonymous"属性
- 确保你的图片CDN服务器支持CORS访问,也就是会返回Access-Control-Allow-Origin等响应头;
- img标签src后面加上一个固定的字符串:‘http://xxx.com/fjksndfnsknfskdfks11231.png?any_string’,防止击穿CDN缓存
html2canvas只能截取可视区域的页面,生成之前记得 window.scrollTo(0, $(this).offset().top);