我对javascript还是很陌生。
我正在从这里https://developer.mozilla.org/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript/Bounce_off_the_walls编写JavaScript教程。
更具挑战性的练习之一是使球从墙壁反弹时改变颜色。到目前为止,我设法做到这一点:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function ballColor(){
var newColor = getRandomColor();
return newColor;
}
function drawBall(){
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle=ballColor();
ctx.fill();
ctx.closePath();}
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
drawBall();
x += dx;
y += dy;
if(y+dy>canvas.height-ballRadius||y+dy<ballRadius){
dy = -dy;
}
if(x+dx>canvas.width-ballRadius||x+dx<ballRadius){
dx = -dx;}
};
setInterval(draw,30);
如果我运行函数draw(),则球将为每一帧更改颜色,使其非常“闪烁”。
我如何从getRandomColor()获取固定颜色并将其存储在变量中(比如说fixedColorOnly),以便球将只显示fixedColorOnly,直到撞到另一堵墙为止?届时,fixedColorOnly将存储getRandomNumber()中的另一种颜色并反弹。
提前致谢。
最佳答案
只需为颜色创建另一个全局变量。快速重构:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="myCanvas" style="border: 1px solid black"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d"),
x = canvas.width / 2,
y = canvas.height - 30,
dx = 2,
dy = -2,
ballRadius = 10,
color = getRandomColor();
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
x += dx;
y += dy;
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
color = getRandomColor();
}
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
color = getRandomColor();
}
};
setInterval(draw, 30);
</script>
</body>
</html>