I think I’ve covered most of the large technical aspects of JavaScript and canvas that I will be covering for the month. I’ll probably finish up with a bunch of random experiments utilizing all the stuff we’ve covered up till now. But who knows, I might come up with another topic or two as we go along.
Today, we’ll create a kind of artsy network/node diagram that looks like this:
Here’s the code:
[php lang=“JavaScript”]$(function () {
var i, canvas, context, points = [], width, height;
canvas = $("#canvas")[0];
context = canvas.getContext(“2d”);
width = canvas.width;
height = canvas.height;
context.strokeStyle = “rgba(0, 0, 0, 0.2)”;
setInterval(function() {
var p0, p1, dx, dy, dist, max = 150;
p0 = {x:Math.random() * width, y:Math.random() * height};
for(i = 0; i < points.length; i += 1) { p1 = points[i]; dx = p1.x - p0.x; dy = p1.y - p0.y; dist = Math.sqrt(dx * dx + dy * dy); console.log(dist); if(dist < max) { context.beginPath(); context.lineWidth = 1.0 - dist / max; context.moveTo(p0.x, p0.y); context.lineTo(p1.x, p1.y); context.stroke(); } } points.push(p0); }, 1000/24); });[/php] We start out with an array called points. On each frame, we create a random x, y point. Then we loop through the existing points in the array and find out the distance from each one to the new one. If it is less than a maximum distance, we’ll draw a line between the two. The trick to making it look cool is to first start out with a very low alpha on the stroke style: context.strokeStyle = “rgba(0, 0, 0, 0.2)”; And then to vary the line width according to the length of the line with this formula: context.lineWidth = 1.0 - dist / max; This is in a conditional which ensures that dist is less than max. So dist / max will range somewhere between 0 and 1. We subtract that value from 1.0. This means that the further the points are from each other, the thinner the line will be, and as they get closer together, the line width approaches 1. You can see it working here, but note that it is completely unoptimized and will definitely crank your CPU. The longer it runs, the more points it will need to iterate through on each frame, so it’s just going to get worse and worse. Don’t let it run too long! http://www.bit-101.com/jscanvas/mar25.html