Mohandez Remerio Xanthos Mohandez Remerio Xanthos - 1 year ago 104
Javascript Question

HTML flexible canvas scale

I am making a website which will load some blueprint images on a canvas.

but the images are vary in height and width.i Would like to make the canvas scaling equal to the uploaded image scale. How do i code to make the canvas width and height changeble respective to uploaded image.
This done in html5

Answer Source

If I understand you correctly, you want to load images with various dimensions. According to the dimension, set the width / height of the canvas and draw the image?

In that case you could add an eventListener to the image. Once it's loaded, get the width and height. Use those to set the dimensions of the canvas. After that, draw the image on the canvas.

var image = new Image();

image.addEventListener('load', function(e) {
  var width = image.width;
  var height = image.height;

  var canvas = document.querySelector('canvas');
  canvas.width = width;
  canvas.height = height;

  canvas.getContext('2d').drawImage(image, 0, 0, width, height); 

image.src = '';