Ruben G Ruben G - 3 months ago 10
Javascript Question

Canvas wont display image inside of it

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<canvas id="spriteCanvas" width="500" height="500">
<img id="coin" width="440" height="40" src="coin.png">
</canvas>

</body>
</html>


I tried placing an image inside a canvas element, but it won't display on the browser. I know the image tag works because it's displayed if I place it outside of the canvas element. Also, if I inspect the canvas element, I can see that the image is inside, but its dimensions are 0 by 0. Can somebody explain why this isn't working?

EDIT: My original code added the image through javascript, but it wouldn't show on the canvas. It was giving me the same problems as above. But I just realized I was missing "onload".

original code:

var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');

function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}

Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}

function init() {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}

init();


editted code:

var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');

function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}

Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}

coinImage.onload = function () {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}

Answer

This isn't how a <canvas> tag works. If you want your image to appear in your canvas, you will have to use JavaScript to place the pixels of the image into your canvas.

<canvas>s are exactly what they state: canvases. They are an element for you to draw on programmatically. If you just want to display an image on a page, you don't need a canvas, you just need the <img> tag. In fact, elements should not be placed in <canvas>.

Take a look at CanvasRenderingContext2D.drawImage() and this tutorial: HTML5 Canvas Image Tutorial.

And this snippet:

var canvas = document.getElementById("painting"),
  ctx = canvas.getContext("2d"),
  image = new Image();

image.onload = function() {
  ctx.drawImage(image, 30, 50);
};

image.src = "http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.png?v=10a9e8743fb0";
<canvas id="painting" width="300" height="300"></canvas>

Comments