HTML and CSS Reference
In-Depth Information
context.lineTo(partB.x, partB.y);
context.stroke();
var ax = dx * springAmount,
ay = dy * springAmount;
partA.vx += ax;
partA.vy += ay;
partB.vx -= ax;
partB.vy -= ay;
}
}
Now, the nodes are connected, but the lines snap on and off as nodes come in and out of range of each
other—we can make this look better with a gradient between them. If two nodes are under minDist apart,
the line should be almost completely transparent. As they get closer and closer, the line should become
brighter and brighter. So, if we calculate dist/minDist , this gives us a fraction from 0 to 1 for alpha. But
this is backward, because if dist equals minDist , alpha is 1. As dist approaches 0, alpha approaches 0.
Take that number and subtract it from 1, which reverses the effect.
Remember when we discussed colors on the canvas in Chapter 4. In order to use transparency, we need
to format the color as a CSS-style RGBA string. So we pass the color and alpha value to the
utils.colorToRGB function that we included in the utils.js file. Here's the final line-drawing code:
var alpha = 1 - dist / minDist;
context.strokeStyle = utils.colorToRGB("#ffffff", alpha);
context.beginPath();
context.moveTo(partA.x, partA.y);
context.lineTo(partB.x, partB.y);
context.stroke();
This is a beautiful effect, as shown in Figure 12-5. The result is in 07-node-garden-lines.html .
Search WWH ::




Custom Search