简体   繁体   English

将图像绘制到HTML画布

[英]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. 我已经回顾了其他SO帖子和MDN文档等,但仍然无法弄清楚为什么我的图像没有出现在画布中。 I appreciate any help on this. 我很感激任何帮助。

HTML HTML

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

JavaScript 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/ https://jsfiddle.net/rsL3vsju/

This is happening because you are setting the canvas' height and width with CSS, like this: 发生这种情况是因为您使用CSS设置画布的高度和宽度,如下所示:

<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: 正确的方法是使用画布的heightwidth属性,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM