• 使用 html2canvas 点击保存时把当前页面生成图片


     style:
      #box{
        background-image:url('./img/pone.png')
      
     }
     
    body:
      <div id="box">
             <p>我想把页面生成图片</p>
             <input id="btn" value="保存" onclick="getPhoto()" />
      <div>
     js: 
        首先引入:<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script> 
       function getPhoto(){
      drawCanvas("#box")
       }
      
     /* 根据window.devicePixelRatio获取像素比*/
        function DPR() {
            if (window.devicePixelRatio && window.devicePixelRatio > 1) {
                return window.devicePixelRatio;
            }
            return 1;
        }
        /* 将传入值转为整数*/
        function parseValue(value) {
            return parseInt(value, 10);
        };
        /* 绘制canvas*/
        async function drawCanvas(loding) {
            // 获取想要转换的 DOM 节点
            const dom = document.querySelector(loding);
            const box = window.getComputedStyle(dom);
            $('#btn').hide();
            // DOM 节点计算后宽高
            const width = parseValue(box.width);
            const height = parseValue(box.height);
            // 获取像素比
            const scaleBy = DPR();
            // 创建自定义 canvas 元素
            var canvas = document.createElement('canvas');
            // 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
            canvas.width = width;
            canvas.height = height;
            canvas.id = 'can';
            // 设定 canvas css宽高为 DOM 节点宽高
            canvas.style.width = `${width / 100}rem`;
            canvas.style.height = `${height / 100}rem`;
            // 获取画笔
            const context = canvas.getContext('2d');
            // 将所有绘制内容放大像素比倍
            // context.scale(scaleBy, scaleBy);
            let x = width;
            let y = height;
            return await html2canvas(dom, {
                backgroundColor: null,
                canvas,
                useCORS: true
            }).then(function (canvas) {
                let newSrc = convertCanvasToImage(canvas, x, y).src;
                return newSrc;
            })
        }
        /*图片转base64格式*/
        function convertCanvasToImage(canvas, x, y) {
            let image = new Image();
            image.setAttribute("crossOrigin", 'Anonymous');
            image.width = x;
            image.height = y;
            image.src = canvas.toDataURL("image/png");
            return image;
        }
  • 相关阅读:
    初心不负 笔记-JS高级程序设计-引用类型篇-Array
    CSS-样式篇
    笔记-JS高级程序设计-变量,作用域和内存问题
    笔记-JS高级程序设计-基本概念篇
    WPF 10天修炼 第四天- WPF布局容器
    WPF 10天修炼 第三天- Application全局应用程序类
    WPF 10天修炼 第二天- XAML语言
    WPF 10天修炼 第一天- 入门
    C# 关于e.Handled 的说明
    C# Replace方法
  • 原文地址:https://www.cnblogs.com/whx123/p/12054979.html
Copyright © 2020-2023  润新知