sdqali / hugo

Website
http://sdqali.in
2 stars 3 forks source link

Fitting an Image in to a Canvas object #85

Open sdqali opened 5 years ago

sdqali commented 5 years ago

Comments for Fitting an Image in to a Canvas object

raliqala commented 4 years ago

Hello @sdqali i see only the javascript code, how do i use it with html like in your demo? am sorry i'm new can i use this with php

sdqali commented 4 years ago

Hello, @LavoTP. You can find a complete example here. I do not see why you can't use it in PHP. Best.

raliqala commented 4 years ago

Ok thanks @sdqali Your code is great and understandable, i learned something new today. One more question can it work with input type file ?

robstarkdev commented 4 years ago

Terrific! Thank you for this! One thing to note: Canvas seems to REQUIRE the explicit attributes height and width like this: width="450" height="300" And NOT != like this: style="width: 600px; height: 900px;", and NOT in the css stylesheet

Tuily commented 1 year ago

Thanks, it really helped me! I had to make some updates to suit my needs.

Here is a typescript version if anyone needs.

type FitImageOnCanvasParams = {
  canvas: Canvas;
  image: Image;
};

export const fitImageOnCanvas = ({
  canvas,
  image,
}: FitImageOnCanvasParams): void => {
  const context = canvas?.getContext('2d');
  if (!context) {
    console.error('fitImageOnCanvas: no context');
    return;
  }

  const imageAspectRatio = image.width / image.height;
  const canvasAspectRatio = canvas.width / canvas.height;
  let renderableHeight, renderableWidth, xStart, yStart;

  if (imageAspectRatio < canvasAspectRatio) {
    // if image aspect ratio is less than canvas we fit on width and place the image centrally along height
    renderableWidth = canvas.width;
    renderableHeight = image.height * (renderableWidth / image.width);
    xStart = 0;
    yStart = (canvas.height - renderableHeight) / 2;
  } else if (imageAspectRatio > canvasAspectRatio) {
    // if image aspect ratio is greater than canvas we fit on height and place the image centrally along width
    renderableHeight = canvas.height;
    renderableWidth = image.width * (renderableHeight / image.height);
    xStart = (canvas.width - renderableWidth) / 2;
    yStart = 0;
  } else {
    // Image is same aspect ratio as canvas
    renderableHeight = canvas.height;
    renderableWidth = canvas.width;
    xStart = 0;
    yStart = 0;
  }

  context.drawImage(image, xStart, yStart, renderableWidth, renderableHeight);
};