Why ball doesn't change color? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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 Answers
+ 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