Crop Canvas / Export html5 canvas with certain width and height

canvas crop image
canvas drawimage
fill canvas with image
html5 canvas drag, drop and resize images
cropper js example
canvas draw image from url
html canvas image
convert image to canvas

There are hundreds of tutorials, how one can crop an image by drawImage() on a canvas.

context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);

However, I have a canvas that fills the user's browser. By exporting the canvas as an image I would like to export only an area of 640px*480px from (0|0).

Problem: How can I tell javascript to use only 640*480 of the canvas for the toDataURL()?

Here is what I have so far:

$("#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);

    // not working, seems to clear the canvas? browser hangs?
    // seems that I can click a white image in the background
    /*canvas[0].width = 640;
    canvas[0].height = 480;*/

    // not working either
    /*canvas[0].style.width  = '640px';
    canvas[0].style.height = '480px';*/

    // not working at all
    /*context.canvas.width = 640;
    context.canvas.height = 480;*/

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

PS: I do not want to resize or scale, just clipping/cropping to the fixed window. Here I read that you only specifiy canvas.width and canvas.height - but this clears the 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>');
})​

Crop Canvas / Export HTML5 Canvas with certain width and height, For this, create a temporary canvas for drawing on the current canvas. After that use toDataUrl() method on the temporary canvas −var c  To crop an image using HTML5 Canvas, we can add six additional arguments to the drawImage()method, sourceX, sourceY, sourceWidth, sourceHeight, destWidthand destHeight. These arguments define the location and size of a rectangle that we want to cut out of an image.

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

How do I resize images and the image canvas?, We do this by creating an HTML5 <canvas> element and drawing the image to the There are some techniques to improve the quality of images Finally, we resize the image, but only if the new width and height are not  The key to cropping an image using the HTML5 Canvas is the drawImage() method. It accepts an image object, plus six additional parameters: sourceX, sourceY, sourceWidth, sourceHeight, destWidth and destHeight. We can use these parameters to define the exact location and size of a rectangle that we want to crop from the larger image:

You make a second off-screen canvas, you copy the image from the first canvas to the second (using the first as your image object), then you export the second canvas.

HTML5 Canvas Image Crop Tutorial, To crop an image using HTML5 Canvas, we can add six additional arguments to the drawImage() These arguments define the location and size of a rectangle that we want to cut out of an image. var destX = canvas.width / 2 - destWidth / 2; var context = canvas. getContext ( '2d' ); var x = 188; var y = 30; var width = 200; var height = 137; var imageObj = new Image (); imageObj. onload = function () {. context. drawImage ( imageObj, x, y, width, height ); };

Pure html5 canvas crop:

$('document').ready( function(){
const divOffset = 1
var x1,x2,y1,y2, xDif, yDif = 0;
var isSelection, 
    isBottomRight, 
    isTopRight, 
    isTopLeft, 
    isBottomLeft = false

var r = document.getElementById('source').getBoundingClientRect();
var pos = [0, 0];
pos[0] = r.left; 
pos[1] = r.top; //got position coordinates of canvas

var sel = document.getElementById('sel')
var canvasSource = document.getElementById("source");
var ctxSource = canvasSource.getContext("2d"); 

var img = new Image()
img.src = "http://bohdaq.name/assets/localImage.jpg"
img.onload = function(){
  ctxSource.drawImage(img, 0, 0)
}

$( "#source" ).mousedown(function(event) {
   isSelection = true

   x1 = event.pageX - pos[0]
   y1 = event.pageY - pos[1]

   sel.style.setProperty('display', 'block')

   sel.style.setProperty('left', event.pageX + "px")
   sel.style.setProperty('top', event.pageY + "px")

   sel.style.setProperty('width', '0px')
   sel.style.setProperty('height', '0px')
});

$( "#source" ).mouseup(function(event) {
   isSelection = false
   if(isBottomRight){
     x2 = event.pageX - pos[0]
     y2 = event.pageY - pos[1]

     xDif = x2-x1
     yDif = y2-y1 
   } else if (isBottomLeft){
     y2 = event.pageY - pos[1]
     yDif = y2 - y1 

     xDif = x1 - x2
     x1 = x1 - xDif

   } else if(isTopRight){
     x2 = event.pageX - pos[0]
     xDif = x2 - x1 
     yDif = y1 - y2
     y1 = y1 - yDif         
   } else if (isTopLeft){
     xDif = x1 - x2
     x1 = x1 - xDif
     yDif = y1 - y2
     y1 = y1 - yDif         
   }
   sel.style.setProperty('display', 'none')
   crop(x1, y1, xDif, yDif)
});

$('#source').mousemove(function(event){
  if(isSelection){
    x2 = event.pageX - pos[0]
    y2 = event.pageY - pos[1]
    if(x2>x1 && y2>y1){ //moving right bottom selection
      isBottomRight = true
      isBottomLeft = false
      isTopLeft = false
      isTopRight = false

      xDif = x2 - x1
      yDif = y2 - y1 

      sel.style.setProperty('width', xDif + 'px')
      sel.style.setProperty('height', yDif + 'px')
    } else if(x2<x1 && y2>y1){ //moving left bottom selection
      isBottomLeft = true
      isTopLeft = false
      isTopRight = false
      isBottomRight = false

      xDif = x1 - x2
      yDif = y2 - y1 

      sel.style.setProperty('left', x2 + 'px')
      sel.style.setProperty('width', xDif + 'px')
      sel.style.setProperty('height', yDif + 'px')

    } else if(x2>x1 && y2<y1){
      isTopRight = true
      isTopLeft = false
      isBottomLeft = false
      isBottomRight = false

      xDif = y1 - y2
      yDif = x2 - x1 

      sel.style.setProperty('top', y2 + 'px')
      sel.style.setProperty('width', yDif + 'px')
      sel.style.setProperty('height', xDif + 'px')
    } else if (x2<x1 && y2<y1){
      isTopLeft = true
      isTopRight = false
      isBottomLeft = false
      isBottomRight = false

      yDif = y1 - y2 
      xDif = x1 - x2

      sel.style.setProperty('left', x2 + pos[0] + divOffset + 'px')
      sel.style.setProperty('top', y2 + pos[1] + divOffset + 'px')
      sel.style.setProperty('width', xDif  + 'px')
      sel.style.setProperty('height', yDif  + 'px')
    }
 }
})

function crop(x, y, xDif, yDif){
    canvasSource.width = xDif
    canvasSource.height = yDif
    ctxSource.drawImage(img, x, y, xDif, yDif, 0, 0, xDif, yDif);
}

})

HTML5 Canvas Get Image Data URL, In this article, I will explain how I did some of that, repeat some canvas basics and show The HTML needed for the examples in this article is basic: querySelector('canvas');; canvas.height = canvas.width = 0;; var context = canvas. To resize an image, all you need to do is to define a different size in the parameters of  Width, Height or Both options ensures that the entire content is scaled down to the canvas size and is visible even when you view on a small screen (such as mobile devices or tablets). If the screen size is larger than the authored stage size, canvas is displayed in the original size.

based on @GarySkiba answer:

// crop canvas function
const cropCanvas = (
  canvas: any,
  x: number,
  y: number,
  width: number,
  height: number
) => {
  // create a temp canvas
  const newCanvas = document.createElement('canvas');
  // set its dimensions
  newCanvas.width = width;
  newCanvas.height = height;
  // draw the canvas in the new resized temp canvas 
  newCanvas
    .getContext('2d')!
    .drawImage(canvas, x, y, width, height, 0, 0, width, height);
  return newCanvas
};

use it like:

// get canvas from somewhere
const canvas = ....;
// crop the left top 50x50 rect
const newCanvas = cropCanvas(canvas, 0, 0, 50, 50 );
// get the relative image
newCanvas.toDataURL('image/png')

Resizing and Cropping Images with Canvas, In some cases you may want to export an image that is more suited to <canvas id="FaceCompositionCanvas" width="300" height="400"  I use html5 canvas elements to resize images im my browser. It turns out that the quality is very low. I found this: Disable Interpolation when Scaling a <canvas> but it does not help to increase the quality.

Canvas, images and pixels, HTML Canvas Reference. Example. The code below copies the pixel data for a specified rectangle on the canvas with getImageData(x,y,width,height);  Image Properties Title: Canvas Dimensions width: height: Jun 18, 2014 · 2. Click the tool icon to “Overwrite this Project. In order to save the image to server, we need to pass captured image data with a form field. Jan 24, 2020 · A JavaScript library that helps developers convert any HTML element into an image using HTML5 Canvas and SVG API.

HTML5 Canvas Export to High Quality Image Tutorial, Known image size increase: When exporting the cropped image on browser-side 0 : no restrictions; 1 : restrict the crop box to not exceed the size of the canvas. The maximum width is the initial width of the preview container. the Orientation value with 1 (the default value) to avoid some issues (1, 2) on iOS devices. If the height or width of the canvas is 0 or larger than the maximum canvas size, the string "data:," is returned. If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported. Chrome also supports the image/webp type. Syntax canvas.toDataURL(type, encoderOptions); Parameters

HTML canvas getImageData() Method, CSS determines the size the canvas is displayed. You can set the size of the canvas's drawingbuffer in 2 ways. One using HTML. <canvas id="c" width="400"  The canvas spec doesn't give us a method for measuring the height of a string. However, you can set the size of your text in pixels and you can usually figure out what the vertical bounds are relatively easily.

Comments
  • Awesome, works very well! / The only thing that irritates me is that Firefox indicates loading the page (tab shows turning circle) when the image already showed up. Clicking ESC shows wyciwyg:// in the url!? ... "wyciwyg is an internal URI scheme used to represent document.write result pages" / But anyway, happy that you gave me a working solution!