Cropping an image

function cropImage() {
var canvas=document.getElementById("myCanvas");
var c=canvas.getContext("2d");

var imageObj = new Image();
imageObj.onload = function() {
// draw reference image
c.drawImage(imageObj,50,30, 438, 300);

// draw cropped image
var sourceX = 150;
var sourceY = 0;
var sourceWidth = 150;
var sourceHeight = 150;
var destX = 370;
var destY = 220;
var destWidth = sourceWidth;
var destHeight = sourceHeight;

c.drawImage(imageObj, sourceX, sourceY, sourceWidth,
sourceHeight, destX, destY, destWidth, destHeight);
imageObj.src = "darth-vader.jpg";

save as data url

Using the HTML5 canvas element, you can create all sorts of cool graphics client-side on the fly using Javascript. However, the canvas image cannot (in all browsers) simply be saved to disk as any other image.
Luckily there is a neat function on the the canvas object called toDataURL(). This functions encodes the image data as a base64 encoded PNG file and returns it as a data: URI.

var strDataURI = oCanvas.toDataURL();
// returns "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt..."

Other formats than PNG are supported by some browsers by adding an argument to the toDataURL() call containing the mime type of the format you want.

var strDataURI = oCanvas.toDataURL("image/jpeg");
// returns "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA..."

It looks like Opera and Safari only supports PNG, while Firefox supports at least PNG and JPEG.

Related Blogs

  • Related Blogs on

Leave a Reply

Your email address will not be published. Required fields are marked *