Solo  当前访客:3 开始使用

使用html2casvas将html元素写入canvas并转化为图片


1、html2canvas

官网

2、使用中的问题

1)图片、文字模糊

解决: 根据屏幕像素比,缩放相应的倍数

 var getPixelRatio = function (context) {
                    var backingStore = context.backingStorePixelRatio ||
                        context.webkitBackingStorePixelRatio ||
                        context.mozBackingStorePixelRatio ||
                        context.msBackingStorePixelRatio ||
                        context.oBackingStorePixelRatio ||
                        context.backingStorePixelRatio || 1;
                    console.log("backingStore=="+backingStore+",window.devicePixelRatio=="+window.devicePixelRatio)
                    return (window.devicePixelRatio || 1) / backingStore;
                };
// srcEl 需要被写入的元素
var originalWidth = srcEl.width();
                 var originalHeight = srcEl.height();
             var scaledCanvas = document.createElement("canvas");
             var scaledContext = scaledCanvas.getContext("2d");

             scaledContext.webkitImageSmoothingEnabled = false;
             scaledContext.mozImageSmoothingEnabled = false;
             scaledContext.imageSmoothingEnabled = false;

             var scaleFactor = getPixelRatio(scaledContext);
          
             scaledCanvas.width = originalWidth * scaleFactor;
             scaledCanvas.height = originalHeight * scaleFactor;
             scaledCanvas.style.width = originalWidth + "px";
             scaledCanvas.style.height = originalHeight + "px";
           
             scaledContext.scale(scaleFactor, scaleFactor);

html2canvas(srcEl[0], {canvas: scaledCanvas})
.then(function (canvas) {
var imgData = canvas.toDataURL('image/png', 1);
})

 

2) 在safair上测试,当包含图片或背景图片跨域时,报 security excetion

解决1、背景图片换成img

      2、img 上加crossOrigin = "anonymous"  或 将讲图片先上传到服务器,在从同域服务器读取


标题:使用html2casvas将html元素写入canvas并转化为图片
作者:hugh0524
地址:https://blog.uproject.cn/articles/2017/06/30/1498804564395.html

, , , , , 0 0