Search code examples
htmlcanvastransformscale

Scaling photo image on html5 canvas at preset location


I have been struggling with this problem for sometime, I hope someone would be able to help me out on this.

I have added canvas object in my html code, in which I load a photo image. I am trying to scale the image at some random coordinates, but the scaling happens only from the center of the canvas. If I use translate the whole image moves as the origin changes. I have also tried transform but that too doesn't give the desired result.


Solution

  • use context.drawImage() + extended parameters to scale your original image onto your canvas

    context.drawImage(srcImage, srcX, srcY, srcWidth, srcHeight, 
          canvasX, canvasY, scaledWidth, scaledHeight)
    

    Where:

    • srcImage = your source image
    • srcX = the X-coord on your source image you want to start grabbing pixels from
    • srcY = the Y-coord on your source image you want to start grabbing pixels from
    • srcWidth = width of a rectangle of pixels you want to start grabbing from the source image
    • srcHeight = height of a rectangle of pixels you want to start grabbing from the source image
    • canvasX - the X coord on the canvas where you want to start painting your pixel rectangle
    • canvasY - the Y coord on the canvas where you want to start painting your pixel rectangle
    • scaledWidth - scale the source pixel rectangle to this width before painting to the canvas
    • scaledHeight - scale the source pixel rectangle to this height before painting to the canvas

    For example:

    context.drawImage(myMap, 50,50,100,150,  20,20,200,300)
    

    This will grab a 100x150px rectangle of pixels from myMap image object starting at coordinate [50,50].

    Then it will scale the pixel rectangle to 200x300px.

    And finally, it will paint the scaled-up pixel rectangle at coordinate [20,20] on the canvas