所以我试图让它每次点击它都会改变颜色。但是我遇到了让循环工作的问题。它工作一次,但后来不起作用,我尝试了一些不同的方法但却无法使其工作多次。任何帮助都会很棒!
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
<canvas id="myCanvas" width="800" height="490" style= background:black;>
</canvas>
<script>
</script>
<script>
function colorChecker(colorChanger) {
if (colorChanger == 1) {
ctx.fillStyle = 'green';}
if (colorChanger == 2) {
ctx.fillStyle = 'red';}
if (colorChanger == 3) {
ctx.fillStyle = 'yellow';}
if (colorChanger == 4) {
ctx.fillStyle = 'purple';}
if (colorChanger == 5) {
ctx.fillStyle = 'blue';}
}
var onOff = true;
var c = document.getElementById("myCanvas");
c.addEventListener('click',function() {
var colorChanger = 1;
if (colorChanger < 6) {
colorChanger++;
colorChecker(colorChanger);
}
else {
colorChanger = 1;
colorChecker(colorChanger);
}
}
);
var ctx = c.getContext("2d");
ctx.fillStyle = 'green';
var fallingWords = ["Java", "if", "else", "elsif", "True", "False", "null", "C++", "Python", "Math.random()", "X", "Y", "while", "do", "for", "loop", "import", "var", "let", "()", "{}", "arrays", "and", "or", "not"];
var things = [];
var objectNumber = 150;
for (var i = 0; i < objectNumber; i++) {
var a = {};
//randomly pick one tag
a.code = fallingWords[Math.round(Math.random() * fallingWords.length)];
a.x = Math.random() * 800;
a.y = Math.random() * 490 - 490;
a.speed = Math.random() * 10;
things.push(a);
}
setInterval(function () {
ctx.clearRect(0, 0, 800, 490);
for (var i = 0; i < objectNumber; i++) {
var a = things[i];
ctx.fillText(a.code, a.x, a.y);
a.y += a.speed;
if (a.y > 600) a.y = -50;
}
}, 90);
if (onOff === false) {
objectNumber = 0;
}
else {
objectNumber = 150;
}
</script>
</body>
</html>
答案 0 :(得分:0)
在您的事件监听器中,colorChanger
始终 1:
.addEventListener('click',function() {
//THIS NEEDS TO BE DECLARED OUTSIDE THIS FUNCTION
var colorChanger = 1;
if (colorChanger < 6) {
colorChanger++;
colorChecker(colorChanger);
}
else {
colorChanger = 1;
colorChecker(colorChanger);
}
}
);