我正在尝试将图像文件“ 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>
您需要在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>
有时作为workAround,我们必须在画布之前加载图像。这是非常不寻常的,但是WORKS。然后,您只需隐藏图像。不要忘记使用setTimeOut等待图像加载!