Hi All,
I’m creating a plugin similar to this FabricJS: Drawing & Painting Canvas. I plan to release it for free/open-source.
Unfortunately, I just started and already hit a roadblock with mouse events. I can draw lines, but they only render on mouseUp.
Any help would be appreciated.
Here’s what I have under Initialize (with some help from chatGPT trying to solve the issue ):
function(instance, context) {
// Create a new fabric.js canvas
var canvas = new fabric.Canvas(instance.canvasId, {
backgroundColor: 'white' // Set the background color of the canvas to white
});
// Add the canvas to the DOM
$(instance.canvas).append(canvas.getElement());
// Set the canvas dimensions
var canvasWidth = 512;
var canvasHeight = 512;
canvas.setDimensions({ width: canvasWidth, height: canvasHeight });
// Enable drawing mode on the canvas
canvas.isDrawingMode = true;
//Disable select mode on the canvas
canvas.selection = true;
// Adjust the drawing scale and offset based on the canvas dimensions
canvas.freeDrawingBrush.width = 10;
canvas.freeDrawingBrush.color = 'black';
canvas.freeDrawingBrush.shadow = null;
canvas.freeDrawingBrush.offset = new fabric.Point(0, 0);
canvas.freeDrawingBrush.globalCompositeOperation = 'source-over';
// Create a rectangle object
var rectangle = new fabric.Rect({
left: 10,
top: 10,
width: 100,
height: 100,
fill: 'black',
selectable: true // Make the rectangle selectable
});
// Add the rectangle to the canvas
canvas.add(rectangle);
// Bind event listeners to the canvas element
canvas.getElement().addEventListener('mousedown', function(event) {
canvas.__onMouseDown(event);
});
canvas.getElement().addEventListener('mousemove', function(event) {
canvas.__onMouseMove(event);
});
canvas.getElement().addEventListener('mouseup', function(event) {
canvas.__onMouseUp(event);
});
// Override the _finalizeAndAddPath method to update canvas rendering during drawing
var originalFinalizeAndAddPath = canvas._finalizeAndAddPath;
canvas._finalizeAndAddPath = function() {
originalFinalizeAndAddPath.call(this);
this.renderAll();
};
}