0

How can we prevent this circle to not torch the canvas border?

https://code.sololearn.com/WB64J0kuqbB3/?ref=app

1st Jan 2021, 7:30 AM
Abbakar_ah!!!
Abbakar_ah!!! - avatar
2 Réponses
+ 2
This should do the trick: window.onload = () => { let canvas = document.getElementById("canvas") canvas.height = window.innerHeight; canvas.width = window.innerWidth; let c = canvas.getContext("2d") for(let i=0; i<=20; i++){ let radius = 30 let radiusWithBorder = radius + 1; let x = Math.random() * (window.innerWidth - radiusWithBorder * 2) + radiusWithBorder; let y = Math.random() * (window.innerHeight - radiusWithBorder * 2) + radiusWithBorder; let colors = ["blue", "green", "black"] if((x + radius) < window.innerWidth && (y + radius) < window.innerHeight){ c.beginPath() c.arc(x, y, 30, 0, Math.PI * 2, false) c.strokeStyle = "blue" c.fillStyle = colors[Math.floor(Math.random() * 4)] c.fill() c.stroke() } } } The changes I made are: 1. Adjusted range of the random calculation so it wasn't 0 to inner width but rather radiusWithBorder to inner width - radiusWithBorder 2. Minor refactoring. Moved the radius declaration to make it easier to use for calculating the radius with its stroke width included.
1st Jan 2021, 3:50 PM
Josh Greig
Josh Greig - avatar
0
Josh Greig wow! I can see now it work nicely thank you👍👍👍
1st Jan 2021, 3:57 PM
Abbakar_ah!!!
Abbakar_ah!!! - avatar