Why ball doesn't change color? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
0

Why ball doesn't change color?

I need when ball hit wall, will change color let canvas = document.getElementById("myCanvas"); let ctx = canvas.getContext("2d"); let ballRadius = 10; let x = canvas.width/2; let y = canvas.height-30; let dx = 2; let dy = -2; function changeColor() { let colors = ['red', 'blue', 'purple', 'green', 'pink'] let randomIndex = Math.floor(Math.random() * colors.length); let randomColor = colors[randomIndex]; } function drawBall() { ctx.beginPath(); ctx.arc(x, y, ballRadius, 0, Math.PI*2); ctx.fillStyle = "purple"; ctx.fill(); ctx.closePath(); } function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawBall(); if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) { dx = -dx; changeColor(); } if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) { dy = -dy; changeColor(); } x += dx; y += dy; } setInterval(draw, 10);

13th Jan 2024, 8:13 AM
Дэй
Дэй - avatar
2 Respuestas
+ 5
First of all remember to write your code in the playground and share here. Second, check this and read comments: https://sololearn.com/compiler-playground/W1Xicwbqx5KW/?ref=app
13th Jan 2024, 9:14 AM
🇮🇱 Radin Masiha 🇮🇱
🇮🇱 Radin Masiha 🇮🇱 - avatar
+ 1
Thank you
14th Jan 2024, 8:42 AM
Дэй
Дэй - avatar