Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

javascript - 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 :(
Here's my code :

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

So, how to crop the dataURL ?
Can anyone help me ?
Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The toDataURL method will always capture the whole canvas.

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.

enter image description here

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...