omid
omid

Reputation: 45

scaling image inside canvas according to browser width and height

I have a canvas and there is an image inside it.Let's say it's 800px in width and 520px in height. How should I scale the image that has been drawn by canvas according to browser's height and width so I can see the image correct with any browser size?

Thanks

Upvotes: 0

Views: 364

Answers (1)

nstosic
nstosic

Reputation: 2614

Haven't tested this but you could do it kind of like android development specifies its resolution handling. Let's say your resolution of reference (1x modification) is 1920x1080 and you have fixed resolution for that size (you mentioned 800x520) . Then you can multiply those values with modifying factors for other resolutions:

<canvas id="myCanvas"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var x = 0; //x coordinate of the picture
  var y = 0; //y coordinate of the picture
  var screenWidth = window.innerWidth || document.body.clientWidth;
  var screenHeight = window.innerHeight || document.body.clientHeight;
  var multiplication = ((screenWidth / 1920) + (screenHeight / 1080)) / 2;
  var width = 800 * multiplication;
  var height = 520 * multiplication;
  var imageObj = new Image();
  imageObj.onload = function() {
    context.drawImage(imageObj, x, y, width, height);
  };
  imageObj.src = '[your source here]';
</script>

The pitfall here is if the window size does not have the same aspect ratio (16:9) . Like you see the multiplication factor takes the average of the relative ratio between width and 1920 value and height and 1080 value. Also make sure to refresh canvas on client window resize, although the browser should take care of that by itself (it will redraw).

Upvotes: 0

Related Questions