您好,
我想canvas.toDataURL()
在将其发送到服务器之前裁剪我,但我没有找到如何:(
这是我的代码:
TakePhoto: function() { var myCanvas = document.getElementById('game'); var dataURL = myCanvas.toDataURL(); // crop the dataURL }
那么,如何裁剪dataURL?
谁能帮我 ?
提前致谢
该toDataURL
方法将始终捕获整个画布.
因此,要捕获裁剪部分,您必须创建一个临时画布并将其大小调整为与裁剪相同的大小.
然后使用扩展形式drawImage
来裁剪原始图像并将其绘制到临时画布上.
示例代码和演示:
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://img.devbox.cn/3cccf/16086/243/3acb21bfbb644443.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; }
Original image
Cropped image create from cropping .toDataURL