How to get actual size of image in canvas?

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

How to get actual size of image in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 3 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.