How to get actual size of image in canvas?

by cortez.connelly , in category: Javascript , 9 months ago

How to get actual size of image in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 9 months ago

@cortez.connelly 

To get the actual size of an image displayed on a canvas, you can use the naturalWidth and naturalHeight properties of the HTMLImageElement object. Here's how you can do it:

  1. Load the image onto an HTML canvas element:
1
2
3
4
5
6
7
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
  ctx.drawImage(img, 0, 0);
};
img.src = 'image.jpg';


  1. Get the actual size of the image:
1
2
3
4
var actualWidth = img.naturalWidth;
var actualHeight = img.naturalHeight;
console.log('Actual width: ' + actualWidth + 'px');
console.log('Actual height: ' + actualHeight + 'px');


By using the naturalWidth and naturalHeight properties of the image object, you can retrieve the original dimensions of the image before it was scaled or modified on the canvas.

Related Threads:

How to get canvas image data?
How to get image mask in canvas?
How to get full image after zooming in canvas?
How to get the actual chart width and height in chart.js?
How to get the total bundle size when building with vite?
How to change the size of canvas?