Mixing programming languages for fun and profit
By joe
- 2 minutes read - 367 wordsI’ve been looking for a simple HTML5-ish way to represent our disk drives in our Unison units. I’ve been looking for some simple drawing libraries in javascript to make this higher level, so I don’t have to handle all the low level HTML5 bits. I played with Raphael and a few others (including paper.js). I wound up implementing something in Raphael.
The code that generated this was a little unwieldly … as javascript doesn’t quite have all the constructs one might expect from a modern language. And thanks to its object orientation, its … er … somewhat more verbose than it really needs to be.
<div style="width:<% $win{x} %>px; height:< % $win{y} %>px" id="chassis"></div>
<script>
var paper = Raphael({
container: "chassis",
width: < % $win{x} %>,
height:< % $win{y} %>
});
var disks = [], labels = [], hoverArea = [], lx =[], ly = [];
var x0,y0,x1,y1,label,count;
for (var row = 1; row < = <% $dim{rows} %> ; row++) {
for (var col = 1; col < = <% $dim{cols} %> ; col++) {
x0 = Math.round(< % $xpar{margin} %> + (col-1) * (< % $xpar{width} + $xpar{spacing} %>) + 0.5);
y0 = Math.round(< % $ypar{margin} %> + (< % $dim{rows} %> -(row-1)) * (< % $ypar{height} + $ypar{spacing} %>) + 0.5);
x1 = Math.round(< % $xpar{width} %> + 0.5 );
y1 = Math.round(< % $ypar{height} %> + 0.5 );
lx[count] = Math.round(x0 + x1/3 + 0.5 );
ly[count] = Math.round(y0 + y1/3 + 0.5 );
label = "R".concat(row.toString()).concat("\nC").concat(col.toString());
disks[count] = paper.rect(x0,y0,x1,y1)
.attr({fill: "green", opacity: 0.2, stroke: 1}) .hover( function () {
this.attr({fill: "blue", opacity: 0.2, stroke: 1}); },
function () {
this.attr({fill: "green", opacity: 0.2, stroke: 1});
} );
labels[count] = paper.text(lx[count],ly[count],label);
count++;
}
}
</script>
Note that there are some constructs there not in javascript. They are the < % $variable %> bits. This is what we use to pass data from the perl template code (Mojolicious and HTML::Mason) into the HTML (and Javascript). I guess I am finding it humorous that I am having Perl rewrite the Javascript as it emits it. This is minor, variable substitution, but I’ve done more major bits of editing which javascript goes out over the wire.