0

I have a script that renders a image onto a canvas context. I want to change the width of the canvas to match the dimensions of the image. I use the following script to do so:

var c = document.getElementById("c");
var ctx = c.getContext("2d");
function loadImage(url){
    var img = new Image();
    img.src = url;
    return img;
};
var image = loadImage("images/bird.png");
c.width = image.width + "px";
c.height = image.height + "px";
{...}

However, the canvas' dimentions are set to "0", even if I go into the console and type c.width = "10px" or something around those lines.

Fuzzyzilla
  • 356
  • 4
  • 15
  • Note that `canvas.width` is not the same thing as `canvas.style.width`. Make sure you're setting the one you intend to set. (You may need to set both). – James Thorpe Aug 03 '15 at 20:25
  • @James Thorpe I am aware of this, and using `canvas.style.width` does not change the aspect ratio of the canvas, while `canvas.width` does. – Fuzzyzilla Aug 03 '15 at 20:26
  • Ok. Have you tried it without the `+ "px"` at all? I believe the `width`/`height` attributes may not need it. Could be that it's setting it to 0 because it sees `..px` as invalid. – James Thorpe Aug 03 '15 at 20:31
  • try removing `+ "px"` – maioman Aug 03 '15 at 20:32
  • A value for `canvas.width/height` should not contain unit + what nrabinowitz has said in their answer. – Teemu Aug 03 '15 at 20:32
  • @Teemu Oh, I thought it should have that because when making the original HTML element it is required. Thank you! However, it did not change the outcome. It still sets the dimentions to 0x0... – Fuzzyzilla Aug 03 '15 at 20:34
  • [Is it?](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas). I'm pretty sure it's needed only for the `style` values. – Teemu Aug 03 '15 at 20:41

1 Answers1

2

I think you're expecting the image dimensions to be available synchronously, but they won't be available until the image is loaded asynchronously. See Getting an image dimensions

You're going to want something like:

function loadImage(url, canvas) {
    var img = new Image();
    img.src = url;
    // Set a callback function to run when the
    // image is loaded
    img.onload = function() {
        canvas.width = img.width + "px";
        canvas.height = img.height + "px";
    }
};

loadImage("images/bird.png");
Community
  • 1
  • 1
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165