Skip to content

Instantly share code, notes, and snippets.

@torus
Created February 11, 2011 11:24
Show Gist options
  • Save torus/822222 to your computer and use it in GitHub Desktop.
Save torus/822222 to your computer and use it in GitHub Desktop.
リブルラブル風塗りつぶし。
<html>
<head>
<title>fill</title>
</head>
<body>
<h1>fill</h1>
<p><span id="fps-span"></span> FPS</p>
<canvas id="field"></canvas>
<script type="text/javascript" src="polyfill.js"></script>
</body>
</html>
function is_inside (point, lines, dist) {
var x = point[0]
var y = point[1]
var result = 0
for (var i = 0; i < lines.length; i ++) {
var line = lines[i]
var a = line[0]
var b = line[1]
var c = line[2]
// var d = -1
var d = a * x + b * y + c
if (d < 0)
return false
else if (d < dist)
result = 1
}
return result > 0
}
function draw_canvas (canvas, thickness) {
var vertices = [[20, 280], [400, 20], [600, 360], [300, 400], [20, 280]]
var p1 = vertices[0]
var lines = []
for (var i = 1; i < vertices.length; i ++) {
var p2 = vertices[i]
var x1 = p1[0]
var x2 = p2[0]
var y1 = p1[1]
var y2 = p2[1]
var vx = x2 - x1
var vy = y2 - y1
var vlen = Math.sqrt (vx * vx + vy * vy)
var ux = vy
var uy = -vx
var line = [- ux / vlen, - uy / vlen, ((x1 * ux) + (y1 * uy)) / vlen]
lines.push (line)
p1 = p2
}
var w = canvas.width
var h = canvas.height
var ctx = canvas.getContext ("2d")
var img = ctx.getImageData (0, 0, w, h)
var imgdata = img.data
for (var y = 0; y < 400; y ++) {
for (var x = 0; x < 640; x ++) {
// var v = true
var v = is_inside ([x, y], lines, thickness)
var base = y * w * 4 + x * 4
if (v) {
imgdata[base] = 0
imgdata[base + 1] = 0
imgdata[base + 2] = 255
imgdata[base + 3] = 255
} else {
imgdata[base] = 0
imgdata[base + 1] = 255
imgdata[base + 2] = 200
imgdata[base + 3] = 255
}
}
}
ctx.putImageData (img, 0, 0)
}
function test_canvas () {
var field = document.getElementById ("field")
field.width = 640
field.height = 400
var ctx = field.getContext ("2d")
ctx.fillStyle = "rgb(200, 255, 255)"
ctx.fillRect (0, 0, field.width, field.height)
var fpselem = document.getElementById ("fps-span")
var start = Date.now ()
var prev = start
var t = 0
var intid = setInterval (function () {
draw_canvas (field, t)
t += 1
if (t > 40) {
clearInterval (intid)
}
var curtime = Date.now ()
fpselem.textContent = 1 / (curtime - prev) * 1000
prev = curtime
}, 33)
}
test_canvas ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment