user1554966
user1554966

Reputation: 433

HTML5 images and scaling issues

When i draw an image in a canvas, i have to specify the canvas width and height so it matches with the image size that im trying to paint.

<script>
  window.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var imageObj = new Image();

    imageObj.onload = function() {
      context.drawImage(imageObj, 0, 0);
    };
    imageObj.src = "<%=image_path('logo.jpg')%>";

  };

</script>
<canvas id="myCanvas" width="700" height="400"></canvas>

specifying the canvas width and height is not so good because i might need to use different values than those depending on the resolution of the screen, i need to work on proportions, so i would like to know how to handle this and also how to paint an image without having to specify the width and height to the canvas.

Upvotes: 0

Views: 232

Answers (2)

jbalsas
jbalsas

Reputation: 3502

You don't necessarily need to specify the canvas width and height. You can change it anytime through its width and height properties. You can also have a fixed-size canvas and then scale your images so that they fit in it or get stretched.

You can see in this fiddle several scenarios.

  1. Initially the canvas has no width and height
  2. When the image gets loaded, it activates the "auto" mode, which means that it changes the canvas size to the size of the image

Then, you can play with the buttons to trigger other scale modes

  • Fit: Fits the image in a 400x400 canvas and centers it
  • Stretch: Resizes the image so it fills the 400x400 canvas completely
  • Real: The image is rendered in its original size but the canvas dimensions are 400x400
  • Auto: The canvas size matches the size of the image

I hope this can help you get some ideas.

Upvotes: 0

henry bemis
henry bemis

Reputation: 488

i would suggest using percentages to specify height and width. these will define values as a percent of the containing block.

also, any time you give these attributes certain values, the type should be explicitly defined (e.g. width="700px").

use caution, though, as these may distort your image, depending on how you define your attributes.

best of luck.

Upvotes: 0

Related Questions