javascript - 如何让 javascript 随机发生器出现图像

标签 javascript image random

所以我试图制作某种网络应用程序(随机字符选择器) 但我不知道如何在不覆盖整个网站的情况下显示图像,对我有什么想法吗?这是我已有的 javascript

function RandomCustoms() {
                            canvasRuimte = document.getElementById('canvas').getContext('2d');
                            canvasRuimte.clearRect(0,0,600,300);
                            canvasRuimte.font = 'italic 30px sans-serif';
                            canvasRuimte.fillStyle = "BLACK";
                            worp1 = Math.floor(24*Math.random())+1;
                            tekenAfbeelding(worp1);
                            worp2 = Math.floor(24*Math.random())+1;
                            tekenAfbeelding(worp2);
                            worp3 = Math.floor(24*Math.random())+1;
                            tekenAfbeelding(worp3);
                            worp4 = Math.floor(24*Math.random())+1;
                            tekenAfbeelding(worp4);
                            worp5 = Math.floor(24*Math.random())+1;
                            tekenAfbeelding(worp5);
                            function tekenAfbeelding(worp1){
                                document.write('<img id="image"src="Paladins-champions/'+worp1+'.png" >');
                            }
                            function tekenAfbeelding(worp2){
                                document.write('<img id="image"src="Paladins-champions/'+worp2+'.png" >');
                            }
                            function tekenAfbeelding(worp3){
                                document.write('<img id="image"src="Paladins-champions/'+worp3+'.png" >');
                            }
                            function tekenAfbeelding(worp4){
                                document.write('<img id="image"src="Paladins-champions/'+worp4+'.png" >');
                            }
                            function tekenAfbeelding(worp5){
                                document.write('<img id="image"src="Paladins-champions/'+worp5+'.png" >');
                            }
                        }

提前致谢

最佳答案

您可以仅替换一个元素的 HTML,而不会覆盖您的文档。

在 HTML 中,您应该创建一个容器来保存要显示的图像:

<div id="imgContainer"></div>

然后,您可以使用 javascript 添加图像:

document.getElementById('imgContainer').innerHTML = '<img id="image"src="Paladins-champions/'+worp1+'.png" >';

getElementById 查找具有特定 id 的元素,innerHTML 替换该元素内的 HTML。

您可以在此处查看更多示例和文档:https://www.w3schools.com/js/js_htmldom_html.asp .

关于javascript - 如何让 javascript 随机发生器出现图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43214212/

相关文章:

javascript - 尝试通过 javascript 呈现 Bootstrap 模式时未定义

html - Bootstrap 自动调整背景图像

Python:将 RAW 图像转换为 PNG

python - 如何使用 Pygame 中的列表项进行 collideect() ?

python - 在 Python 字典中随机随机排列键和值

javascript - javascript中null和 ""的区别

javascript - JS 类型错误 : Cannot read property 'style' of null - Chrome

javascript - Firebase 上的 forEach 方法调用带有未定义键的子快照的回调

java - 我想当用户单击 GUI 中的按钮时打开图像

algorithm - 以随机顺序生成整数序列,无需预先构建整个列表