Skip to content

Instantly share code, notes, and snippets.

@OneHoopyFrood
Created July 1, 2014 17:58
Show Gist options
  • Save OneHoopyFrood/fd69ae42db82005c0330 to your computer and use it in GitHub Desktop.
Save OneHoopyFrood/fd69ae42db82005c0330 to your computer and use it in GitHub Desktop.
Creates a ruler of the specified dimensions using paper.js (Written in paperscript)
// Paper.js Ruler object.
// Creates a ruler of the specified dimensions using paper.js
function Ruler(params) {
// Length of the ruler (px)
this.lengthOfRuler = params.lengthOfRuler;
// Space between ticks (px)
this.tickSpacing = params.tickSpacing;
// Show the number on the [nth] tick
this.numOnTick = params.numOnTick;
// Tick height (px)
this.tickHeight = params.tickHeight;
// How much each tick represents
this.unit = params.unit;
// Default values
if (typeof this.lengthOfRuler == 'undefined')
this.lengthOfRuler = paper.view.size.width - 50;
if (typeof this.tickSpacing == 'undefined')
this.tickSpacing = 5;
if (typeof this.numOnTick == 'undefined')
this.numOnTick = 5;
if (typeof this.tickHeight == 'undefined')
this.tickHeight = 10;
if (typeof this.unit == 'undefined')
this.unit = 1;
// A place to keep the ticks together
this.group = new Group();
// Function to actually draw the ruler
this.Draw = function (originX, originY) {
// Starting NW corner of the ruler. Default to center of the view
if (typeof originX == 'undefined')
originX = (paper.view.size.width - this.lengthOfRuler) / 2 ;
if (typeof originY == 'undefined')
originY = (paper.view.size.height / 2) - (this.tickHeight / 2);
// Total number of ticks on the ruler
var numTicks = this.lengthOfRuler / this.tickSpacing;
// Once for each tick
for (var i = 0; i < numTicks; i++) {
// Where to start the tick path
var xPos = originX + i * this.tickSpacing;
var yPos = originY;
var start = new Point(xPos, yPos);
// Where to end the tick path
var end;
// Determine if this is a long numbered tick
if (i % this.numOnTick == 0) {
end = new Point(xPos, yPos + this.tickHeight + (this.tickHeight / 2));
var num = new PointText();
num.fillColor = 'black';
num.content = (parseFloat((i * this.unit).toFixed(this.unit.countDecimals()))).toString();
num.position = new Point(xPos, yPos + this.tickHeight + (this.tickHeight / 2) + (num.handleBounds.height / 2));
}
else
end = new Point(xPos, yPos + this.tickHeight);
// A new path for each tick
var tick = new Path.Line(start, end);
tick.strokeColor = 'black';
tick.strokeWidth = 1;
// Store in the group
this.group.addChild(tick);
}
}
}
// Helper function added to the Number object
Number.prototype.countDecimals = function () {
if (Math.floor(this.valueOf()) === this.valueOf()) return 0;
return this.toString().split(".")[1].length || 0;
}
var ruler = new Ruler({lengthOfRuler: 755, tickSpacing: 5, numOnTick: 10, unit: .1});
ruler.Draw(15,70);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment