🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 一、简单示例 ![](https://box.kancloud.cn/f207f19dba1f7bd415990193adee1bec_414x219.jpg) ~~~ var canvas = document.createElement('canvas'); var wth = 500, hgt = 360; canvas.width = wth; canvas.height = hgt; document.body.appendChild(canvas); var ctx = canvas.getContext('2d'); var data = "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" + "<foreignObject width='100%' height='100%'>" + "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" + "<em>I</em> like <span style='color:white; text-shadow:0 0 2px blue;'>cheese</span>" + "</div>" + "</foreignObject>" + "</svg>"; ctx.fillStyle = '#ddd'; ctx.fillRect(0, 0, wth, hgt); var img = new Image(); var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"}); var url = window.URL.createObjectURL(svg); img.crossOrigin = 'anonymous'; img.src = url; img.onload = function() { window.URL.revokeObjectURL(url); ctx.drawImage(img, 0, 0); window.open(canvas.toDataURL('image/jpeg', 0.75)); } ~~~ ## 二、截屏 使用封装好的类库 **html2canvas**:http://html2canvas.hertzen.com/ 示例: ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>截屏</title> <script src="js/jquery.min.js"></script> <script src="js/html2canvas.min.js"></script> </head> <body> <button type="button" id="js_capture_screen">截屏</button> <a id="js_download_snapshoot" href="" style="display: none;"></a> <script> // 点击截取body内容 $('#js_capture_screen').click(function() { html2canvas(document.body).then(function(canvas) { $('#js_download_snapshoot').attr({ href: canvas.toDataURL(), download: 'img-snapshoot.jpg' }); $('#js_download_snapshoot')[0].click(); // document.body.appendChild(canvas); }); }); </script> </body> </html> ~~~ 动态生成a标签实现下载 ~~~ // 点击截取body内容 $('#js_capture_screen').click(function() { html2canvas(document.body).then(function(canvas) { var triggerDownload = $("<a>").attr({ href: canvas.toDataURL(), download: 'img-snapshoot.jpg' }).appendTo("body"); triggerDownload[0].click(); triggerDownload.remove(); }); }); ~~~ 添加配置项 ~~~ // 点击截取body内容 $('#js_capture_screen').click(function() { html2canvas(document.body, { width: 300, height: 300 }).then(function(canvas) { var triggerDownload = $("<a>").attr({ href: canvas.toDataURL(), download: 'img-snapshoot.jpg' }).appendTo("body"); triggerDownload[0].click(); triggerDownload.remove(); }); }); ~~~