We include the Fabric.js library using a script tag sourced from a CDN. Fabric.js simplifies working with the canvas element by providing a higher-level API for drawing and manipulating objects on the canvas.
In the JavaScript section, we initialize a new Fabric.js canvas object using the canvas element's id. We set the default drawing properties, such as enabling the drawing mode and specifying the brush's width and color.
The changeColor() function is used to change the drawing color based on the button clicked. If the "Eraser" button is clicked, the brush color is set to white to act as an eraser.
The clearCanvas() function clears the canvas by calling the clear() method on the Fabric.js canvas object.
This code provides a basic drawing and sketching tool with color selection, eraser functionality, and canvas clearing. You can further enhance it by adding additional features like different brush sizes, saving and loading drawings, and more.
<!DOCTYPE html>
<html>
<head>
<title>Drawing and Sketching Tool</title>
<style>
#canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>
<div>
<button onclick="changeColor('red')">Red</button>
<button onclick="changeColor('green')">Green</button>
<button onclick="changeColor('blue')">Blue</button>
<button onclick="changeColor('black')">Black</button>
<button onclick="changeColor('white')">Eraser</button>
<button onclick="clearCanvas()">Clear Canvas</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.4.0/fabric.min.js"></script>
<script>
// Initialize Fabric.js canvas
const canvas = new fabric.Canvas('canvas');
// Set default drawing properties
canvas.isDrawingMode = true;
canvas.freeDrawingBrush.width = 5;
canvas.freeDrawingBrush.color = 'black';
// Function to change drawing color
function changeColor(color) {
if (color === 'white') {
// Set the drawing brush to eraser mode
canvas.freeDrawingBrush.color = 'white';
} else {
canvas.freeDrawingBrush.color = color;
}
}
// Function to clear the canvas
function clearCanvas() {
canvas.clear();
}
</script>
</body>
</html>
No comments:
Post a Comment