该demo放于tomcat下运行,否则出现跨域错误
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body style="height: 100%; margin: 0"> <div style="text-align: center;"> <canvas id="myCanvas" width="500" height="300" style="border: 1px solid #fff123"></canvas> <div> <button id="btn" onclick="download()">点我下载</button> </div> </div> <script type="text/javascript"> let cans=document.getElementById("myCanvas"); let ctx=cans.getContext("2d"); let img =new Image(); img.src="2.jpg"; img.setAttribute("crossOrigin",'Anonymous'); img.onload = function(){ //以Canvas画布上的坐标(10,10)为起始点,绘制图像 ctx.drawImage(img, 10, 10); ctx.drawImage(img,50,50,100,100); ctx.strokeStyle = "#0695FF"; //定义矩形的颜色 ctx.strokeRect(50,50,100,100); ctx.strokeRect(50,170,100,100); }; function imgType(ty) { let type = ty.toLowerCase().replace(/jpg/i, 'jpeg'); var r = type.match(/png|jpeg|bmp|gif/)[0]; return 'image/' + r; } function download() { let type = 'png'; //设置下载图片的格式 let img_png_src = cans.toDataURL("image/png"); //将canvas保存为图片 let imgData = img_png_src.replace(imgType(type),'image/octet-stream'); let filename = '图片' + '.' + type; //下载图片的文件名 saveFile(imgData,filename); } let saveFile = function(data, fileName){ let save_link = document.createElement('a'); save_link.href = data; save_link.download = fileName; let event = document.createEvent('MouseEvents'); event.initEvent("click", true, false); save_link.dispatchEvent(event); }; </script> </body> </html