Bresenhams Circle Alg
by Andrew Poes
HTML
<canvas id="canvas" width="480" height="320"></canvas>
CSS
.print {
position: relative;
display: inline-block;
background-color: black;
color: white;
font-family: Helvetica, Helvetica-Neue, sans-serif;
font-weight: bold;
font-size: 24px;
letter-spacing: -1.5px;
padding: 4px 8px;
}
body {
background-color: #eeeeee;
}
#canvas {
background-color: #f3f3f3;
}
}
JavaScript
$(document).ready(function() {
if (window.devicePixelRatio == 2) {
var canvas = document.getElementById('canvas')
canvas.style.width = "480px";
canvas.style.height = "320px";
canvas.setAttribute('width', 960);
canvas.setAttribute('height', 640);
var ctx = canvas.getContext('2d')
ctx.scale(2, 2);
}
update()
})
var cx = 240
var cy = 160
var radius = 50
var pen = 1
var tick = 0
var jag = 0.1
function update() {
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
ctx.clearRect(0,0,480,320)
++tick
cx = 240 + Math.sin(tick * 0.05) * 10
cy = 160 + Math.sin(tick * 0.1) * 10
radius = 50 + Math.abs(Math.cos(tick * 0.05) * 50)
pen = Math.max(Math.abs(Math.sin(tick * 0.05) * 5), 1.5)
jag = 2
drawCircle(cx, cy, radius, jag, pen)
drawCircle(cx, cy, radius, 1, 0.5)
setTimeout(update, 20)
}
function drawCircle(x0, y0, radius, inc, pen) {
var x = radius
var y = 0
// Decision criterion divided by 2 evaluated at x=r, y=0
var decisionOver2 = 1 - x
while (x >= y) {
var points = [
[x, y],
[y, x],
[-x, y],
[-y, x],
[-x, -y],
[-y, -x],
[x, -y],
[y, -x]
]
for (var i = 0; i < points.length; ++i) {
var point = points[i]
if (tick%points.length == i) {
drawPixel(point[0] + x0, point[1] + y0, pen)
}
drawPixel(point[0] + x0, point[1] + y0, 0.5)
}
y += inc
if (decisionOver2 <= 0) {
decisionOver2 += 2 * y + 1
}
else {
x -= inc
decisionOver2 += 2 * (y - x) + 1
}
}
}
function drawPixel(x, y, s) {
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
ctx.fillStyle = "rgb(40,100,240)"
ctx.fillRect(x - s / 2, y - s /...