附源码: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> .mark{ position:absolute; height:100px; width:100px; left:100px; top:180px; border:1px solid #000; cursor:move; } </style> </head> <body> <canvas id="c1"></canvas> //显示原图像 <div class="mark" id="mark"></div> <canvas id="c3"></canvas> //显示剪切后的图像 <input type="button" οnclick="downloadpng('ss')" value="下载"/> <script> function downloadpng(name){ var url = getCanvasUrl({l:10,t:10},{w:100,h:100}); var image = new Image() // 解决跨域 Canvas 污染问题 image.setAttribute('crossOrigin', 'anonymous') image.onload = function () { var canvas = document.createElement('canvas') canvas.width = image.width canvas.height = image.height var context = canvas.getContext('2d') context.drawImage(image, 0, 0, image.width, image.height) var url = canvas.toDataURL('image/png') // 生成一个a元素 var a = document.createElement('a') // 创建一个单击事件 var event = new MouseEvent('click') // 将a的download属性设置为我们想要下载的图片名称,若name不存在则使用‘下载图片名称’作为默认名称 a.download = name || '下载图片名称' // 将生成的URL设置为a.href属性 a.href = url // 触发a的单击事件 a.dispatchEvent(event) } image.src = url; } function getCanvasUrl(position,size){ var l = position.l || 0; var t = position.t || 0; var w = size.w || 10; var h = size.h || 10; var canvas1 = document.getElementById("c1"); var cxt1 = canvas1.getContext("2d") var dataImg = cxt1.getImageData(l,t,w,h); var canvas2 = document.createElement("canvas") var cxt2=canvas2.getContext("2d") canvas2.width = w; canvas2.height = h; cxt2.putImageData(dataImg,0,0,0,0,canvas2.width,canvas2.height) return canvas2.toDataURL("image/png"); } var canvas1 = document.getElementById("c1") var oMark = document.getElementById("mark") var canvas3 = document.getElementById("c3") canvas1.height = 300; canvas1.width=300; canvas3.height=100; canvas3.width=100; var cxt1 = canvas1.getContext("2d") var img = new Image(); img.src = "./img/img.png"; var srcX = oMark.offsetLeft-canvas1.getBoundingClientRect().left; var srcY = oMark.offsetTop-canvas1.getBoundingClientRect().top; var sWidth = oMark.offsetWidth; var sHeight = oMark.offsetHeight; var canvas2 = document.createElement("canvas") var cxt2=canvas2.getContext("2d") img.onload = function(){ cxt1.drawImage(img,0,0,canvas1.width,canvas1.height); var dataImg = cxt1.getImageData(srcX,srcY,sWidth,sHeight) canvas2.width = sWidth; canvas2.height = sHeight; cxt2.putImageData(dataImg,0,0,0,0,canvas2.width,canvas2.height) var img2 = canvas2.toDataURL("image/png"); var cxt3=canvas3.getContext("2d") var img3 = new Image(); img3.src = img2; img3.onload = function(){ cxt3.drawImage(img3,0,0,canvas3.width,canvas3.height) } } </script> </body> </html>
点击下载按钮: