Today I just want to cover how to change the stroke of lines, both in WireLibJS and in Canvas itself. Really the same thing, since I just pass the values on from the lib to the canvas.
The two properties you use are strokeStyle and lineWidth, where strokeStyle is a string and lineWidth is a number.
There several ways to define the strokeStyle string. The most basic is run of the mill hexadecimal:
wirelib.strokeStyle = “#ff0000”; // creates a red line.
wirelib.strokeStyle = “#00ff00”; // creates a green line
There are also some tricks you can use to use integers from 0 – 255 for the component colors:
wirelib.strokeStyle = “rgb(255, 0, 255)”; // creates a purple line.
And a value from 0.0 – 1.0 for alpha:
wirelib.strokeStyle = “rgba(255, 0, 255, 0.5)”; // creates a purple line, 50% alpha.
There are similar methods if you prefer HSL to RGB. Again, all of this is straight from canvas, not something I made up. So you can check out any canvas reference for all the tricks and tips on that.
And lineWidth is just a number, in pixels, for how wide the line to be drawn will be. By default it’s 1, making a 1 pixel wide line. This is all straightforward.
In WireLibJS, just set the strokeStyle and/or lineWidth and it will affect any subsequent lines, boxes, circles, or rects that are added to the canvas. As of this writing, there is no way to change the color of an existing line. Here’s an example:
[php lang=”javascript”]$(function() {
var i, points = [];
wirelib.initWithCanvas($(“#canvas”)[0]);
wirelib.strokeStyle = “#ff0000”;
for(i = 0; i < 20; i += 1) {
points.push(Math.random() * 500 - 250,
-400 + Math.random() * 500 - 250,
Math.random() * 500 - 250);
}
wirelib.addLine(points);
wirelib.strokeStyle = "rgb(255, 128, 0)";
wirelib.addBox(0, 0, 0, 300, 300, 500);
wirelib.lineWidth = 10;
wirelib.strokeStyle = "rgba(0, 0, 255, 0.5)";
wirelib.addCircle(-200, 400, 0, 200, 32);
wirelib.lineWidth = 0.5;
wirelib.strokeStyle = "#ff00ff";
wirelib.addRect(200, 400, 0, 400, 250);
wirelib.loop(24, function() {
wirelib.rotateY(0.01);
wirelib.draw();
});
});[/php]
Here, the squiggly line is red, the box is orange, the circle is drawn with a 10-pixel thick, 50% transparent blue line, and the rect is done with a 0.5 pixel purple line.
And here it is in action.
Really impressive – thanks for sharing – we are going to experiment with this soon and will re-share any results when possible!
Ian
There’s bug: the blue thick rind sometimes distorted when it rotates, in both Firefox 5 and Chrome.