Search code examples
javascriptimage-processinghtml5-canvascropcropperjs

Cropping an Image using multiple co-ordinates in javascript


I want to crop an Image using the 4 co-ordinate points in javascript

E.g:- topleft,topright,bottomleft,bottomright

I have checked with the drawImage() function which is present in cropper.js but I hope It can return only in square format because it follows

drawImage(sx,sy,sh,sw,nx,ny,nh,nw);

I need a image to be cropped using 4 cordinates.


Solution

  • You can use clip in canvas to do that

    const img = document.querySelector('img')
    const canvas = document.querySelector('canvas')
    const ctx = canvas.getContext('2d')
    canvas.width = img.naturalWidth
    canvas.height = img.naturalHeight
    
    const path = [{
        x: 10,
        y: 10
      },
      {
        x: 290,
        y: 30
      },
      {
        x: 270,
        y: 270
      },
      {
        x: 50,
        y: 10
      },
    ]
    
    ctx.beginPath()
    ctx.moveTo(path[0].x, path[0].y)
    for (const { x, y } of path.slice(0, -1)) {
      ctx.lineTo(x, y)
    }
    ctx.closePath()
    ctx.clip()
    
    ctx.drawImage(img, 0, 0)
    <canvas></canvas>
    <img src="https://mdn.github.io/dom-examples/canvas/pixel-manipulation/assets/rhino.jpg">