美文网首页
html2canvas生成图片模糊

html2canvas生成图片模糊

作者: 雅雅的前端工作学习 | 来源:发表于2019-12-16 16:09 被阅读0次

    其实网上教程很多,但是往往因为没有注明所用html2canvas.js的版本,而导致代码报错
    原理:放大canvas的画布尺寸(尺寸为window.devicePixelRatio),这样 物理像素与设备独立像素(dips)就可以契合的填充,代码如下:

      //截图目标div
        const dom = $("#html2canvas")[0];
        // 创建一个新的canvas
        const Canvas = document.createElement('canvas');
        const width = document.body.offsetWidth;  // 可见屏幕的宽
        const height = document.body.offsetHeight;  // 可见屏幕的高
        const scale = window.devicePixelRatio;  // 设备的devicePixelRatio
        // 将Canvas画布放大scale倍,然后放在小的屏幕里,解决模糊问题
        Canvas.width = width * scale;
        Canvas.height = height * scale;
        Canvas.getContext('2d').scale(scale, scale);
        html2canvas(dom, {
            canvas: Canvas,
            scale,
            useCORS: true,
            logging: true,
            width: width + 'px',
            hegiht: height + 'px',
        }).then((canvas) => {
            const context = canvas.getContext('2d');
            // 关闭抗锯齿形
            context.mozImageSmoothingEnabled = false;
            context.webkitImageSmoothingEnabled = false;
            context.msImageSmoothingEnabled = false;
            context.imageSmoothingEnabled = false;
            // canvas转化为图片,这里使用了Canvas2Image.js哦,不引入会报错的
            const img = Canvas2Image.convertToImage(canvas, canvas.width, canvas.height);
            console.log(img);
            document.body.appendChild(img);
            img.style.cssText = "width:100%;height:100%;position:absolute;top:0;left:0;right:0;bottom:0;opacity:0;";
            alert("海报生成成功,请长按保存");
        })
    

    相关文章

      网友评论

          本文标题:html2canvas生成图片模糊

          本文链接:https://www.haomeiwen.com/subject/dbddnctx.html