简体   繁体   English

如何裁剪 canvas.toDataURL

[英]How to crop canvas.toDataURL

Hello ,你好
I want to crop my canvas.toDataURL() before sending it on the server, but I didn't find how :(我想在将canvas.toDataURL()发送到服务器之前对其进行裁剪,但我没有找到方法:(
Here's my code :这是我的代码:

TakePhoto: function() {
        var myCanvas = document.getElementById('game');
        var dataURL = myCanvas.toDataURL();
        // crop the dataURL
    }

So, how to crop the dataURL ?那么,如何裁剪 dataURL
Can anyone help me ?谁能帮我 ?
Thanks in advance提前致谢

The toDataURL method will always capture the whole canvas. toDataURL方法将始终捕获整个画布。

So to capture a cropped portion you will have to create a temporary canvas and size it to the same size as the crop.因此,要捕获裁剪的部分,您必须创建一个临时画布并将其调整为与裁剪相同的大小。

Then use the extended form of drawImage to both crop the original image and draw it onto the temporary canvas.然后使用drawImage的扩展形式来裁剪原始图像并将其绘制到临时画布上。

在此处输入图片说明

Example code and a Demo:示例代码和演示:

 var img=new Image(); img.crossOrigin='anonymous'; img.onload=start; img.src="https://i.stack.imgur.com/EUBBt.png"; function start(){ var croppedURL=cropPlusExport(img,190,127,93,125); var cropImg=new Image(); cropImg.src=croppedURL; document.body.appendChild(cropImg); } function cropPlusExport(img,cropX,cropY,cropWidth,cropHeight){ // create a temporary canvas sized to the cropped size var canvas1=document.createElement('canvas'); var ctx1=canvas1.getContext('2d'); canvas1.width=cropWidth; canvas1.height=cropHeight; // use the extended from of drawImage to draw the // cropped area to the temp canvas ctx1.drawImage(img,cropX,cropY,cropWidth,cropHeight,0,0,cropWidth,cropHeight); // return the .toDataURL of the temp canvas return(canvas1.toDataURL()); }
 body{ background-color: ivory; } img{border:1px solid red; margin:0 auto; }
 <h4>Original image</h4> <img src='https://i.stack.imgur.com/EUBBt.png'> <h4>Cropped image create from cropping .toDataURL</h4>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM