我目前正在学习Javascript,我能够创建一个简单的游戏,其中的形状和颜色会发生变化,它会四处移动。我被困在如何输入图像......请帮助我! =(谢谢!=)
这是我创建的游戏的网站http://sites.codeschool.org.uk/?site=imat3ap0t
我想将形状更改为3张jpg图片,让它做同样的事情。我太困了!
function getRandomColor() {
var letters = '0123456789ABCDEF'.split(''); //the numbers&letters are for color codes. split is the string (set of numbers and letters into an array)
var color = '#'; //color codes start with #
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 16)];
}
return color;
}
var clickedTime;
var createdTime;
var reactionTime;
function makeBox() {
var time = Math.random();
time = time * 5000;
setTimeout(function () {
if (Math.random() > 0.5) {
document.getElementById("box").style.borderRadius = "100px";
} else {
document.getElementById("box").style.borderRadius = "0";
}
var top = Math.random();
top = top * 300;
var left = Math.random();
left = left * 500;
document.getElementById("box").style.top = top + "px";
document.getElementById("box").style.left = left + "px";
document.getElementById("box").style.backgroundColor = getRandomColor();
document.getElementById("box").style.display = "block";
createdTime = Date.now();
}, time);
}
document.getElementById("box").onclick = function () {
clickedTime = Date.now();
reactionTime = (clickedTime - createdTime) / 1000;
document.getElementById("time").innerHTML = reactionTime;
document.getElementById("box").style.display = "none";
makeBox();
}
makeBox();
谢谢大家的回复!
答案 0 :(得分:0)
你需要修改你的功能:
function getRandomImage() {
// All of the image options
// This is very similar to string of characters you have now
var images = ['path/to/image/1', 'path/to/image/2', 'path/to/image/3']
// Randomly select one image path
// By using images.length we don't have to hardcode the length like the "16" you're using, which is good incase the list changes
var imagePath = images[Math.floor(Math.random() * images.length)];
// Return random image path
return imagePath;
}
那么您可能需要在文档中的某个位置使用img
标记,而不是现在使用的div:
<img id="changing-image"></img>
然后您可以使用更多javascript来查找图片并更改其src
属性:
var image = document.getElementById("changing-image");
image.src = getRandomImage();