How to resize a centered image on a canvas?

Member

by ryleigh , in category: HTML & CSS , a year ago

How to resize a centered image on a canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 10 months ago

@ryleigh 

To resize a centered image on a canvas, you can follow these steps using HTML and CSS:

  1. Create a canvas element in your HTML code:
1
<canvas id="canvas"></canvas>


  1. In your CSS, assign a size to the canvas element and center it:
1
2
3
4
5
6
#canvas {
  width: 400px;
  height: 400px;
  margin: 0 auto;
  border: 1px solid black;
}


  1. Load the image onto the canvas using JavaScript:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

const image = new Image();
image.src = 'path/to/image.png';

image.onload = function() {
  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;
  
  // Calculate the new dimensions for the resized image
  const newWidth = 200; // desired width
  const newHeight = (image.height / image.width) * newWidth; // maintain aspect ratio
  
  // Calculate the top-left corner coordinates to center the image
  const topLeftX = centerX - newWidth / 2;
  const topLeftY = centerY - newHeight / 2;
  
  // Draw the resized image onto the canvas, centered
  ctx.drawImage(image, topLeftX, topLeftY, newWidth, newHeight);
};


In the code above, adjust the width and height of the canvas (#canvas) to your desired size. Also, provide the correct path to your image file in image.src.


This code will load the image, calculate new dimensions to resize it, and draw the resized image onto the canvas centered on the screen.