Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing image to HTML canvas

I've reviewed the other SO posts and MDN docs, etc on this but still can't figure out why my image is not appearing in the canvas. I appreciate any help on this.

HTML

<canvas id="myCanvas" style="height:500px;width:500px;border:0.5px solid #979797;"></canvas>

JavaScript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function() {
  ctx.drawImage(img, 0, 0);
}
img.src = 'http://i.imgur.com/3dItN1Y.png';

https://jsfiddle.net/rsL3vsju/

like image 804
Tom Coughlin Avatar asked Mar 03 '26 01:03

Tom Coughlin


1 Answers

This is happening because you are setting the canvas' height and width with CSS, like this:

<canvas id="myCanvas" style="height: 500px; width: 500px; border: 0.5px solid #979797;"></canvas>

That is the wrong code. The correct way is using the height and the width attributes of the canvas, as below:

<canvas id="myCanvas" height="500" width="500" style="border: 0.5px solid #979797;"></canvas>
like image 133
Gabriel Marques Avatar answered Mar 04 '26 15:03

Gabriel Marques



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!