Crop Canvas / Export html5 canvas with certain width and height

I created a simple general purpose function that does the crop by returning a new canvas with the cropped area. While it doesn't do the crop "in place", it's simple. Remember to switch to the new context after the call.

const cropCanvas = (sourceCanvas,left,top,width,height) => {
    let destCanvas = document.createElement('canvas');
    destCanvas.width = width;
    destCanvas.height = height;
    destCanvas.getContext("2d").drawImage(
        sourceCanvas,
        left,top,width,height,  // source rect with content to crop
        0,0,width,height);      // newCanvas, same size as source rect
    return destCanvas;
}

For example...

    let myCanvas = document.createElement('canvas');
    myCanvas.width = 200;
    myCanvas.height = 200;
    let myContext = myCanvas.getContext("2d");
    // draw stuff...
    myCanvas = cropCanvas(myCanvas,50,50,100,100);
    myContext = myCanvas.getContext("2d"); 
    // now using the cropped 100x100 canvas

The best way is to just create a temporary canvas to draw onto from the current canvas. The user will never see this temp canvas. Then you just need use toDataUrl() on the temp canvas.

Live Demo

$("#submitGraphic").click( function(){
    var canvas = document.getElementsByTagName("canvas");
    // canvas context
    var context = canvas[0].getContext("2d");
    // get the current ImageData for the canvas
    var data = context.getImageData(0, 0, canvas[0].width, canvas[0].height);
    // store the current globalCompositeOperation
    var compositeOperation = context.globalCompositeOperation;
    // set to draw behind current content
    context.globalCompositeOperation = "destination-over";
    //set background color
    context.fillStyle = "#FFFFFF";
    // draw background/rectangle on entire canvas
    context.fillRect(0,0,canvas[0].width,canvas[0].height);

    var tempCanvas = document.createElement("canvas"),
        tCtx = tempCanvas.getContext("2d");

    tempCanvas.width = 640;
    tempCanvas.height = 480;

    tCtx.drawImage(canvas[0],0,0);

    // write on screen
    var img = tempCanvas.toDataURL("image/png");
    document.write('<a href="'+img+'"><img src="'+img+'"/></a>');
})​