I#39;m unable to get image in canvas in html5, what to do?(我无法在 html5 中的画布中获取图像,该怎么办?)
问题描述
我已经从我的 w3schools 检查了这段代码,它运行良好.
I have checked this code from my w3schools where its working well.
但是当我在浏览器中运行这段代码时,它不起作用.
But when I run this code in my browser, it's not working.
图像未显示在画布中.此外,我在其他地方的 w3schools 浏览器中尝试了相同的代码,但它仍然无法在该浏览器中运行.
The image does not get displayed in the canvas. Also, I tried the same code in w3schools browser somewhere else, but still it's not working in that browser either.
<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<img id="scream" src="flower.jpg" alt="The Scream" width="220" height="277"><p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,10,10);
</script>
</body>
</html>
推荐答案
问题是图片的加载是异步的,所以你的Javascript代码可能在图片加载完成之前就已经运行了.因为当 ctx.drawImage(img, 10, 10)
被称为 img
时没有完整的数据并且在画布上什么也没有.
The problem is that load of an image is asynchronous, so your Javascript code might run before the image finish his loading. Because of that when ctx.drawImage(img, 10, 10)
is called img
have no complete data and draws nothing on canvas.
要解决您需要等待图像完全加载的问题.Javascript 让您能够设置一个函数以在图像完全加载时运行.
To solve that you need to wait the image to completely load. Javascript give you the ability to setup a function to run when an image is completely loaded.
所有依赖于图像数据的代码都应该放在 onload
回调中.
All code that depends of the image data should be put inside the onload
callback.
img.onload = function(){
ctx.drawImage(img,10,10);
}
带有修改部分的脚本:
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
img.onload = function(){
ctx.drawImage(img,10,10);
}
</script>
如果 src
正确,无论图像是从 html 标记加载还是使用 new Image()
在 Javascript 中动态创建,onload
方法适用于两者.
If the src
is correct doesn't matter if the image is loaded from a html tag or created dynamically in Javascript with new Image()
, the onload
method works for both.
这篇关于我无法在 html5 中的画布中获取图像,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我无法在 html5 中的画布中获取图像,该怎么办?
基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01