当前位置: 首页 > 工具软件 > html-to-image > 使用案例 >

html转图片并解决模糊问题

东方华晖
2023-12-01

将下面的标签转成图片

<div class="neirong card-bg" id="neirong">
  <div class="name">1111</div>
  <img src="http://q395jfyvp.bkt.clouddn.com/mbti_img/images/res/aaa.jpeg'" class="index_img">
  <div class="erweima">1111</div>
</div>

引入html2canvas网上有很多

<script src="__ADDONSTATIC__wechat/js/html2canvas.js"></script>
var canvas2 = document.createElement("canvas");
let _canvas = document.querySelector('.card-bg');//需要替换成图片的html区域
//获取宽高
var w = parseInt(window.getComputedStyle(_canvas).width);
var h = parseInt(window.getComputedStyle(_canvas).height);
//将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
canvas2.width = w * 2;
canvas2.height = h * 2;
canvas2.style.width = w + "px";
canvas2.style.height = h + "px";
//可以按照自己的需求,对context的参数修改,translate指的是偏移量
var context = canvas2.getContext("2d");
context.scale(2,2.03);
var rect = copyDom.get(0).getBoundingClientRect();//获取元素相对于视察的偏移量
console.log(rect)
context.translate(-rect.left,-rect.top);//设置context位置,值为相对于视窗的偏移量负值,让图片复位
html2canvas(_canvas,{canvas:canvas2,useCORS: true}).then(function(canvas) {
  var imgUri = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 获取生成的图片的url
  $(".card-bg").html('<img class="down" src="'+imgUri+'" style="width:'+w+'px;">');
})
 类似资料: