这是我的代码,问题出在 ldimg((; 和 img((; ldimg((; 创建图像元素,img((; 得到它,但我的 alert(( 调试测试说无法读取 null 的源代码。
function ldimg(src, name) {
var imageObj = document.createElement('img');
imageObj.onload = function() {
context.drawImage(imageObj, window.innerWidth + 100, window.innerHeight + 1, 1, 1);
};
imageObj.src = src;
imageObj.id = name;
}
function img(name, x, y, width, height) {
var image = document.getElementById(name);
alert(image.src);
}
ldimg('bot.png', 'bot');
function Loop() {
setTimeout(function() {
img('bot', 100, 100, 100, 100);
Loop();
}, 16);
}
Loop();
</script>
</html>
如果您不打算将图像添加到 DOM 中,您可以重构代码以从 ldimg 返回图像。
function ldimg(src, name) {
var imageObj = document.createElement('img');
imageObj.onload = function() {
context.drawImage(imageObj, window.innerWidth + 100, window.innerHeight + 1, 1, 1);
};
imageObj.src = src;
imageObj.id = name;
return imageObj;
}
function img(image, x, y, width, height) {
alert(image.src);
}
var theImg = ldimg('bot.png', 'bot');
function Loop() {
setTimeout(function() {
img(theImg, 100, 100, 100, 100);
Loop();
}, 16);
}
Loop();
</script>
</html>
您需要将图像添加到 DOM 结构中。为此,您可以使用appendChild
如下例所示:
function ldimg(src, name) {
var imageObj = document.createElement('img');
imageObj.src = src;
imageObj.id = name;
var imageDiv = document.getElementById("imgDiv");
imageDiv.appendChild(imageObj);
}
function img(name, x, y, width, height) {
var image = document.getElementById(name);
alert(image.src);
}
ldimg('http://thecatapi.com/api/images/get?format=src&type=gif', 'bot');
<div id="imgDiv"></div>
此外,您设置的setTimeout
应该是一个setInterval
这样您就不必在自身内部调用 a 函数。在下面的示例中,我setInterval
了 10 秒的间隔,以使其稍微不那么烦人:
function ldimg(src, name) {
var imageObj = document.createElement('img');
imageObj.src = src;
imageObj.id = name;
var imageDiv = document.getElementById("imgDiv");
imageDiv.appendChild(imageObj);
}
function img(name, x, y, width, height) {
var image = document.getElementById(name);
alert(image.src);
}
ldimg('http://thecatapi.com/api/images/get?format=src&type=gif', 'bot');
function Loop() {
setInterval(function() {
img('bot', 100, 100, 100, 100);
}, 10000);
}
Loop();
<div id="imgDiv"></div>