cropImage function

CanvasElement? cropImage(
  1. CanvasImageSource image,
  2. int x,
  3. int y,
  4. int width,
  5. int height,
)

Crops the image using coordinates x, y, width and height, returning new image (CanvasElement).

Implementation

CanvasElement? cropImage(
    CanvasImageSource image, int x, int y, int width, int height) {
  if (image is! CanvasElement) {
    var imgDim = getImageDimension(image)!;
    var imgCanvas = CanvasElement(width: imgDim.width, height: imgDim.height);
    var context = imgCanvas.getContext('2d') as CanvasRenderingContext2D;
    context.drawImage(image, 0, 0);
    image = imgCanvas;
  }

  var imgContext = image.getContext('2d') as CanvasRenderingContext2D;
  var imgCropData = imgContext.getImageData(x, y, width, height);

  var canvasCrop = CanvasElement(width: width, height: height);
  var contextCrop = canvasCrop.getContext('2d') as CanvasRenderingContext2D;
  contextCrop.putImageData(imgCropData, 0, 0, 0, 0, width, height);

  return canvasCrop;
}