为什么context.drawImage()在html canvas中不起作用?

问题描述 投票:1回答:2

我正在尝试将图像文件“ sticky.png”放入画布框,但是我得到的只是一块空白画布。谁能指出我做错了什么和/或提供有效的代码?

<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>

<body>

<script>

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.onload = function() {
context.drawImage(sticky, 0, 0);
sticky.src = "sticky.png";
};


</script>

</body>
javascript html5 canvas drawimage
2个回答
3
投票

您需要在sticky.src之前包括sticky.onload

<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
<script>

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.src = "sticky.png";
sticky.onload = function() {
  context.drawImage(sticky, 0, 0);
};

</script>
</body>

Fiddle


0
投票

有时作为workAround,我们必须在画布之前加载图像。这是非常不寻常的,但是WORKS。然后,您只需隐藏图像。不要忘记使用setTimeOut等待图像加载!

© www.soinside.com 2019 - 2024. All rights reserved.