一、使用插件html2canvas:https://github.com/niklasvh/html2canvas
具体代码:
1.html <div class="test"> </div> <img class="down" src="" /> 2.js //创建一个新的canvas var canvas2 = document.createElement("canvas"); let _canvas = document.querySelector('.test'); var w = parseInt(window.getComputedStyle(_canvas).width); var h = parseInt(window.getComputedStyle(_canvas).height); //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了 canvas2.width = w * 2.2; canvas2.height = h * 2.2; canvas2.style.width = w + "px"; canvas2.style.height = h + "px"; //可以按照自己的需求,对context的参数修改,translate指的是偏移量 // var context = canvas.getContext("2d"); // context.translate(0,0); var context = canvas2.getContext("2d"); context.scale(2,2); html2canvas(document.querySelector('.test'),{ canvas:canvas2 }).then(function(canvas) { document.body.appendChild(canvas); document.querySelector('canvas').style.display = "none" //canvas转换成url,然后利用a标签的download属性,直接下载,绕过上传服务器再下载 document.querySelector(".down").setAttribute('src',canvas.toDataURL()); document.querySelector(".test" ).style.display = "none"; });
二、使用dom-to-image
npm下载:https://www.npmjs.com/package/dom-to-image