这是我的代码,问题出在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>
关于javascript - 你能动态创建一个 IMG 元素,并使用 document.GetElementById(name); 访问它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50723337/