gpt4 book ai didi

javascript - Canvas 2D fillStyle 有时不更新颜色

转载 作者:行者123 更新时间:2023-11-28 11:00:52 27 4
gpt4 key购买 nike

我正在使用 2D breakout tutorial from MDN 学习 Canvas 还有一个练习:每次球撞到墙上时,尝试将球的颜色更改为随机颜色。

在抽球之前,我检查球是否在墙内。如果它接触到球,我首先生成一个随机的十六进制值颜色,然后用该颜色绘制球。

但它只是有时有效。我已记录 ctx 对象的 fillStyle 属性,但有时它不会将值更改为新颜色。

/* Reference to Canvas */
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

/* Start Ball Position */
let x = canvas.width / 2;
let y = canvas.height - 30;

/* Move Ball */
let dx = 2;
let dy = -2;

/* Ball Dimensions */
let ballRadius = 10;

/* Ball Color */
let ballColor = "#0095DD";

/* Draw Ball */
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = ballColor;
ctx.fill();
ctx.closePath();
x += dx;
y += dy;
}

/* Update Canvas */
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
bouncing();
drawBall();
}

/**
* If the ball goes outside the boundaries,
* change the direction to the opposite
*/
function bouncing() {
if(x + dx < ballRadius || x + dx > canvas.width - ballRadius) {
dx = -dx;
randomColor();
}

if(y + dy < ballRadius || y + dy > canvas.height - ballRadius) {
dy = -dy;
randomColor();
}
}

/* Change the ball color to a random hex value */
function randomColor() {

const hexColor = ['#'];
const letters = ['A', 'B', 'C', 'D', 'E', 'F'];

for(let digit = 0; digit < 6; digit++) {
let value = Math.floor(Math.random() * 16);
if(value > 9) {
value = letters[value - 9];
}
hexColor.push(value);
}

ballColor = hexColor.join('');

}

setInterval(draw, 10);
html {
box-sizing: border-box;
}

*, *::before, *::after {
box-sizing: inherit;
padding: 0;
margin: 0;
}

canvas {
background: #eee;
display: block;
margin: 0 auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>2D breakout game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="myCanvas" width="480" height="170"></canvas>

<script src="script.js"></script>
</body>
</html>

最佳答案

问题出在 value = letter[value - 9]; 行中。这应该是 value = letter[value - 10];

这是因为您想要的映射是:

10 -> A (letters[0])
11 -> B (letters[1])
12 -> C (letters[2])
13 -> D (letters[3])
14 -> E (letters[4])
15 -> F (letters[5])

所以你需要减去 10 而不是 9。

关于javascript - Canvas 2D fillStyle 有时不更新颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52138659/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com