首先引入jQuery,
其次引入html2canvas.js,
savePic为触发点击事件的按钮,
contaner为整个DIV容器
有需要做则部分的小伙伴可以参考参考
$(".savePic").on("click", function() { var getPixelRatio = function(context) { // 获取设备的PixelRatio var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; return (window.devicePixelRatio || 1) / backingStore; }; var shareContent = $("#contaner")[0]; var width = shareContent.offsetWidth; var height = shareContent.offsetHeight; var canvas = document.createElement("canvas"); var context = canvas.getContext('2d'); var scale = getPixelRatio(context); canvas.width = width * scale; canvas.height = height * scale; canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; context.scale(scale, scale); var opts = { scale: scale, canvas: canvas, width, height: height, dpi: window.devicePixelRatio }; html2canvas(shareContent, opts).then(function(canvas) { context.mozImageSmoothingEnabled = false; context.webkitImageSmoothingEnabled = false; context.msImageSmoothingEnabled = false; context.imageSmoothingEnabled = false; var dataUrl = canvas.toDataURL('image/jpeg', 1.0); var newImg = document.createElement("img"); newImg.src = dataUrl; newImg.width = width; newImg.height = height; alert("截取成功,上拉查看图片"); $("body")[0].appendChild(newImg); }); })
至此,
整个页面就截取到了,可以保存到手机查看图片。