Skip to content

Instantly share code, notes, and snippets.

@astromechza
Created February 1, 2015 20:21
Show Gist options
  • Save astromechza/ce51de45123a249df789 to your computer and use it in GitHub Desktop.
Save astromechza/ce51de45123a249df789 to your computer and use it in GitHub Desktop.
Quick JS webbing demo with canvas.
<!DOCTYPE html>
<html>
<head>
<title>JS Webbing</title>
<style type="text/css">
h1, h5 {
font-family: Verdana;
}
</style>
</head>
<body style="background: #aaa">
<h1>Click and drag your mouse over the canvas below:</h1>
<canvas id="main-canvas" width="800" height="600" style="background: #fff; border: 1px solid #333; border-radius: 5px"></canvas>
<h5>Written by Ben Meier</h5>
<script type="text/javascript">
var canvas = document.getElementById('main-canvas')
var graphics = canvas.getContext("2d")
var known_positions = Array()
var max_connects = 10
var connect_range = 100
var new_point_range = 20
var colours = [
"aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "yellow"
]
var last_position = [0,0]
function util__get_random_colour() {
return colours[Math.floor(Math.random()*colours.length)]
}
function util__get_cursor_position(e) {
var x, y;
if (e.pageX != undefined && e.pageY != undefined) {
x = e.pageX
y = e.pageY
}
else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop
}
x -= canvas.offsetLeft
y -= canvas.offsetTop
return [x+0, y+0]
}
function util__distance(xy1, xy2) {
return Math.sqrt(Math.pow(xy1[0] - xy2[0], 2) + Math.pow(xy1[1] - xy2[1], 2))
}
function canvas__on_click(e) {
if (e.buttons == 1) {
var xy = util__get_cursor_position(e)
if (util__distance(xy, last_position) > new_point_range) {
var c = util__get_random_colour()
graphics.strokeStyle = c
var connected = 0
var xy2, d
for (var i = known_positions.length - 1; i >= 0; i--) {
xy2 = known_positions[i]
d = util__distance(xy, xy2)
if (d < connect_range) {
connected += 1
graphics.beginPath()
graphics.moveTo(xy[0], xy[1])
graphics.lineTo(xy2[0], xy2[1])
graphics.stroke()
if (connected > max_connects) break;
}
};
known_positions.push(xy)
last_position = xy
}
}
}
canvas.addEventListener("mousemove", canvas__on_click, false)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment