Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canvas: image resizing

I'm trying to place an image on a canvas without resizing it. I thought drawImage(img, x, y) would do the trick, but it stretches the image to fill the canvas. Also supplying drawImage(img, x, y, width, height) with the dimensions of my image doesn't seem to work.

Here's my code:

<canvas id="story" style="position:relative; width:800px; height:600px;"></canvas>

<script type="text/javascript">

window.onload = function() {
  var canvas = document.getElementById("story");
  var context = canvas.getContext("2d");
  var img = document.getElementById("img1");
  var width = parseInt(img.width);
  var height = parseInt(img.height);
  context.drawImage(img, 0, 0, width, height);
}

</script>
<img id="img1" alt="" src="http://link to image"/>

Thanks in advance!

PS: I added the parseInt's to make sure that drawImage gets valid values.

like image 584
Markus Avatar asked Nov 12 '10 16:11

Markus


2 Answers

Don't use CSS to size your canvas. That creates a default sized canvas and stretches it. Set the canvas dimensions directly on it and you'll get a 1 to 1 pixel drawing space.

<canvas id="story" width="800" height="600" style="position:relative;"></canvas>
like image 147
Trochoid Avatar answered Nov 17 '22 04:11

Trochoid


Trochoid is right, the style attribute on your canvas tag is causing problems. You could set it in the HTML, as he suggests, or better yet you can leave it blank and set it dynamically in the JS:

<canvas id="story"></canvas>

<script type="text/javascript">

window.onload = function() {
      var canvas = document.getElementById("story");
      var context = canvas.getContext("2d");
      var img = document.getElementById("img1");
      var width = parseInt(img.width);
      var height = parseInt(img.height);

      canvas.height=height;
      canvas.width=width;
      context.drawImage(img, 0, 0);
}

</script>
<img id="img1" alt="" src="http://link to image"/>
like image 14
Jeff Avatar answered Nov 17 '22 05:11

Jeff