Reputation: 1079
I am trying to create a straight line in fabric.js that will switch to line mode using an input checkbox. Problem is, even after I uncheck it, the straight line doesn't stop. How can I make it stop putting out a line after I uncheck?
HTML
<input type="checkbox" id="drawmode">
<canvas id="c" width="500" height="300"></canvas>
JavaScript
var canvas = new fabric.Canvas('c', { selection: false });
var line;
var isDrawing;
document.getElementById('drawmode').addEventListener("click", function(){
if(this.checked == true){
canvas.on('mouse:down', function (o) {
isDrawing = true;
var pointer = canvas.getPointer(o.e);
var points = [pointer.x, pointer.y, pointer.x, pointer.y];
line = new fabric.Line(points, {
strokeWidth: 3,
stroke: 'black'
});
canvas.add(line);
});
canvas.on('mouse:move', function (o) {
if (isDrawing) {
var pointer = canvas.getPointer(o.e);
line.set({ x2: pointer.x, y2: pointer.y });
canvas.renderAll();
}
});
canvas.on('mouse:up', function (o) {
isDrawing = false;
});
}
else if(this.checked == false)
{
// What should I put here to break out of the line drawing mode??
}
Upvotes: 1
Views: 820
Reputation: 8327
Use canvas.off()
to turn off everything, or canvas.off('mouse:down')
to turn off all handlers for a certain event, or canvas.off('mouse:down', handler)
to turn off a certain handler. In the last case, you'll have to put your handlers in variables.
See also the Fabric.js docs.
You could try something like this:
document.getElementById('drawmode').addEventListener("click", function(){
if(this.checked) {
canvas.on('mouse:down', handleMouseDown);
canvas.on('mouse:move', handleMouseMove);
canvas.on('mouse:up', handleMouseUp);
} else {
canvas.off('mouse:down', handleMouseDown);
canvas.off('mouse:move', handleMouseMove);
canvas.off('mouse:up', handleMouseUp);
}
}
function handleMouseDown(o) {
isDrawing = true;
var pointer = canvas.getPointer(o.e);
var points = [pointer.x, pointer.y, pointer.x, pointer.y];
line = new fabric.Line(points, {
strokeWidth: 3,
stroke: 'black'
});
canvas.add(line);
}
function handleMouseMove(o) {
if (isDrawing) {
var pointer = canvas.getPointer(o.e);
line.set({ x2: pointer.x, y2: pointer.y });
canvas.renderAll();
}
}
function handleMouseUp (o) {
isDrawing = false;
}
Upvotes: 1