+ 5

Canvas Colour

I have given vanilla Javascript another try, how can I make the circle be one of the colours from the array (fill not stroke) edit: Another problem, why isn't clearRect working? https://code.sololearn.com/WKOqwX3cLJDV/?ref=app

15th Jun 2019, 1:24 PM
Clueless Coder
Clueless Coder - avatar
6 Answers
+ 7
Like Calvin mentioned, if you just want the ball showing with no trail and nothing filling behind it, use beginPath and closePath. Like this: show(){ c.fillStyle = cols[this.col]; c.beginPath(); c.arc(this.x, this.y, this.w, Math.PI*2, false); c.closePath(); c.fill(); }
15th Jun 2019, 2:26 PM
Josh Greig
Josh Greig - avatar
+ 5
There were 2 lines to fix when I looked at it. 1: From: this.col = Math.floor(Math.random = cols.length); To: this.col = Math.floor(Math.random() * cols.length); You want a random index number. You don't want to replace the Math.random method with something like 5. 2: From: c.fillStyle = this.col; To: c.fillStyle = cols[this.col]; You want to get a colour name like 'red' and not a number for fillStyle. Assuming you want the colour index in this.col, this line would have to change too. This is the complete js code that I got working for easy copy and pasting: //alert("I have not used vanilla Javascript in a very long time, this will be interesting!"); let cols = ["red", "green", "blue", "purple", "cyan", "lightblue", "lightgreen"] let balls = []; window.onload=()=>{ let canvas = document.querySelector("canvas"); let c = canvas.getContext('2d'); class Ball{ constructor(x, y, w, dir){ this.x = x; this.y = y; this.w = w; this.col = Math.floor(Math.random() * cols.length); this.xSpeed = 5; this.ySpeed = 5; this.dir = dir; } show(){ c.fillStyle = cols[this.col]; c.arc(this.x, this.y, this.w, Math.PI*2, false); c.fill(); } move(){ this.x += this.xSpeed; this.y += this.ySpeed; } } let b = new Ball(100, 100, 30); function update(){ requestAnimationFrame(update); c.clearRect(0, 0, innerWidth, innerHeight); b.show(); b.move(); //window.addEventListener("touchstart", ) } update(); }
15th Jun 2019, 1:53 PM
Josh Greig
Josh Greig - avatar
+ 4
c.beginPath();
15th Jun 2019, 2:21 PM
CalviŐ˛
CalviŐ˛ - avatar
+ 4
Josh Greig CalviŐ˛ I have added collision detection to the program, although now it is all messed up. Can you help?
15th Jun 2019, 4:23 PM
Clueless Coder
Clueless Coder - avatar
+ 3
Thanks Josh Greig , does anyone know why clearRect is not working?
15th Jun 2019, 2:00 PM
Clueless Coder
Clueless Coder - avatar
+ 3
Martin Can you help? I know you are good at this
15th Jun 2019, 2:08 PM
Clueless Coder
Clueless Coder - avatar