'use strict'; var util = require('./util'); var TextButton = require('./TextButton'); var config = require('./config'); function RulerHandler(viewport) { var _enabled = false; var _lines = { x: null, y: null }; var _rect = { x: null, y: null }; var Event = { /** * Triggers when handlebar is moved */ onMove: function () { var axis = this.axis; var bounds = viewport.getBounds(); var pos = util.assertBetween(this[axis], bounds.min[axis], bounds.max[axis]); this.marker[axis] = this[axis] = pos; var dim = (this[axis] - bounds[axis]) / (viewport.getData().ppmm * 10 * viewport.canvas.getImage().scaleX); if (axis === 'top') { dim = viewport.getData().dim.height - dim; } this.setText(Math.round(dim * 100) / 100 + ' ' + viewport.getData().dim.units); } }; /** * @return {fabric.Line} */ function getLine(axis) { var bounds = viewport.getBounds(); return new fabric.Line([ 0, 0, axis === 'x' ? bounds.width : 0, axis === 'y' ? bounds.height : 0 ], { evented: false, strokeDashArray: [5, 5], stroke: '#000', strokeWidth: 1, top: axis === 'x' ? bounds.top + bounds.height / 2 : bounds.top, left: axis === 'y' ? bounds.left + bounds.width / 2 : bounds.left }); } /** * @return {RulerHandler} */ this.clear = function () { [].concat(_rect.x, _rect.y, _lines.x, _lines.y).forEach(function (o) { viewport.canvas.remove(o); }); return this; }; /** * @param {Boolean} enabled * @return {RulerHandler} */ this.enable = function (enabled) { _enabled = enabled; this.clear(); if (!_enabled) { viewport.canvas.renderAll(); return; } var bounds = viewport.getBounds(); _lines = { x: getLine('x'), y: getLine('y') }; viewport.canvas.add(_lines.x); viewport.canvas.add(_lines.y); _rect.x = new TextButton('horizontalRuler', 'H', config.rulerHandle) .set(config.rulerHandle.x(_lines, bounds)) .addTo(viewport.canvas) .on('moving', Event.onMove) .trigger('moving'); _rect.y = new TextButton('verticalRuler', 'V', config.rulerHandle) .set(config.rulerHandle.y(_lines, bounds)) .addTo(viewport.canvas) .on('moving', Event.onMove) .trigger('moving'); viewport.canvas.renderAll(); return this; }; /** * @return {RulerHandler} */ this.reset = function () { return this.enable(_enabled); }; } module.exports = RulerHandler;