Skip to content

Instantly share code, notes, and snippets.

@trusktr
Created November 2, 2016 21:00
Show Gist options
  • Save trusktr/a05916e6bb007a5cd7fc4d1eaa7a8477 to your computer and use it in GitHub Desktop.
Save trusktr/a05916e6bb007a5cd7fc4d1eaa7a8477 to your computer and use it in GitHub Desktop.
Draw a circle (pixel algorithm)
//First attempt: O(r^2)
function drawCircle(cx, cy, r) {
var dim = 100
for (let i = -r; i<=r; i+=1) {
for (let j = -r; j<=r; j+=1) {
if (
Math.round(Math.sqrt(i*i + j*j)) === r
) drawPixel(i + cx, j + cy)
}
}
}
function drawPixel(x, y) {
console.log(x, y)
}
//Second attempt: O(r)
function drawCircle(cx, cy, r) {
let x = 0 + r
let y = 0
let eighth = 1
drawPixel(x, y, r, cx, cy)
while (x > y) {
y++
if (!possiblyDrawPixel(x, y, r, cx, cy)) {
x--
drawPixel(x, y, r, cx, cy)
}
}
}
function possiblyDrawPixel(i, j, r, cx, cy) {
if ( Math.round(Math.sqrt(i*i + j*j)) === r) {
drawPixel(i + cx, j + cy)
return true
}
else return false
}
function drawPixel(x, y) {
console.log(x, y)
}
@alexsad
Copy link

alexsad commented Feb 17, 2023

interface RowCol {
     row: number,
     col: number,
}
const drawCircle = (cx: number, cy: number, r: number) => {
    const positions: RowCol[] = [];
    for (let i = -r; i <= r; i += 1) {
        for (let j = -r; j <= r; j += 1) {
            if (
                Math.round(Math.sqrt(i * i + j * j)) === r
            ) {
                positions.push({
                    row: i + cx,
                    col: j + cy,
                })
            }
        }
    }
    return positions;
}
drawCircle(5,5, 4);

works perfect to me!!!!
thanks!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment