Created
November 2, 2016 21:00
-
-
Save trusktr/a05916e6bb007a5cd7fc4d1eaa7a8477 to your computer and use it in GitHub Desktop.
Draw a circle (pixel algorithm)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
works perfect to me!!!!
thanks!!!!