Skip to content

Instantly share code, notes, and snippets.

@Shaked
Created October 27, 2017 22:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shaked/fc5b01aa64e37005122650e9f060ef2d to your computer and use it in GitHub Desktop.
Save Shaked/fc5b01aa64e37005122650e9f060ef2d to your computer and use it in GitHub Desktop.
Create a horizontal & vertical lines attached to mouse move with KonvaJS
var mouseMovingLines = {
enabled: true,
drawn: false,
xaxisLine: null,
yaxisLine: null,
stage: null,
layer: null,
init: function(stage, layer, options) {
this.options = $.extend({
strokeColor: "#fff",
width: 0,
height: 0
}, options);
this.stage = stage;
this.layer = layer;
this.enable();
},
toggle: function() {
if (this.enabled) {
return this.disable();
}
this.enable();
},
disable: function() {
this.stage.off('mousemove');
this.stage.off('mouseenter');
this.destroy();
this.enabled = false;
},
destroy: function(byRequest) {
if (this.xaxisLine) {
this.xaxisLine.destroy();
}
if (this.yaxisLine) {
this.yaxisLine.destroy();
}
this.layer.draw();
this.drawn = false;
},
enable: function() {
this.stage.on('mousemove', this.mouseMove.bind(this));
this.stage.on('mouseenter', this.mouseEnter.bind(this));
this.enabled = true;
},
draw: function() {
var f = this.stage.getPointerPosition();
this.xaxisLine = new Konva.Line({
points: [1, f.y, image.width, f.y],
stroke: this.options.strokeColor,
strokeWidth: 1,
lineCap: 'round',
lineJoin: 'round',
zIndex: 2
});
this.yaxisLine = new Konva.Line({
points: [f.x, 1, f.x, image.height],
stroke: this.options.strokeColor,
strokeWidth: 1,
lineCap: 'round',
lineJoin: 'round',
zIndex: 2
});
var that = this;
this.xaxisLine.on('dbl click', function(e) {
var f = that.stage.getPointerPosition();
// debugger;
console.log('xaxisLine', e);
});
this.yaxisLine.on('dbl click', function(e) {
var f = that.stage.getPointerPosition();
// debugger;
console.log('yaxisLine', e);
});
this.layer.add(this.xaxisLine).add(this.yaxisLine).draw();
this.drawn = true;
},
substructOnePixelToEnsureClicksWork: function(point) {
// return point-1;
return point;
},
mouseMove: function(e) {
if (!this.drawn) {
this.destroy();
this.draw();
}
var f = this.stage.getPointerPosition();
var y = this.substructOnePixelToEnsureClicksWork(f.y);
var x = this.substructOnePixelToEnsureClicksWork(f.x);
this.xaxisLine.points([1, y, this.options.width, y]);
this.yaxisLine.points([x, 1, x, this.options.height],);
this.layer.draw();
},
mouseEnter: function(e) {
this.destroy();
this.draw();
}
};
mouseMovingLines.init(stage, layer, {
width: width,
height: height,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment