h5页面生成海报的插件---html2canvas 及生成的图片模糊问题

安装

npm 安装
npm install --save html2canvas

直接引入html2canvas.js

<script src="http://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<div id="capture" style="padding: 10px; background: #f5da55">
   <h4 style="color: #000; ">Hello world!</h4>
</div>

基本语法

html2canvas(element, options);
html2canvas(document.body, {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  },
  width: 300,
  height: 300
});
//两个参数:所需要截图的元素id,截图后要执行的函数, canvas为截图后返回的最后一个canvas
var opts={
		allowTaint: true; 
		taintTest: false;
		useCORS: true;
			..
			..
}
Html2canvas(document.querySelector("#capture"),opts).then((canvas) =>{
      let oImg = new Image();
      oImg.src = canvas.toDataURL();  // 导出图片
      document.body.appendChild(oImg);  // 将生成的图片添加到body
});

注意事项

html2canvas 在画海报的时候 不能使用网络图片,如果存在网络图片的话,需要把图片保存到本地,或是转成base64编码的格式才可以,

图片https格式转成base64编码格式的 可以采用canvas实现

基本属性 http://html2canvas.hertzen.com/configuration

var ctx= document.createElement("canvas");//生成canvas元素//获取宽高
var d=document.querySelector("#capture")
var w = parseInt(window.getComputedStyle(d).width);//getComputedStyle是一个可以获取当前元素所有最终使用的CSS属性值。
var h = parseInt(window.getComputedStyle(d).height);
//将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
ctx.width = w * 2;
ctx.height = h * 2;
ctx.style.width = w + "px";
ctx.style.height = h + "px";
var context = ctx.getContext("2d");
var opts = {
    canvas: ctx, //自定义 canvas
    useCORS: true // 【重要】开启跨域配置
};
Html2canvas(d,opts).then((canvas) =>{
      let oImg = new Image();
      oImg.src = canvas.toDataURL();  // 导出图片
      document.body.appendChild(oImg);  // 将生成的图片添加到body
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值