I'm learning canvas with the 2D breakout tutorial from MDN and there is an exercise: try changing the color of the ball to a random colour every time it hits the wall.
Before draw the ball, I check if the ball it's inside the wall. And if it touches the ball, first I generate a random hexadecimal value color, and then I draw the ball with that color.
But it only works sometimes. I've logged the fillStyle
property of the ctx
object but sometimes it doesn't change the value to the new color.
/* 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>