preface
I have used this framework to write a DIY card project before. Many problems encountered in the process can only be solved through Google or Github issues. There is little domestic information, so I want to write this article to make a simple summary, hoping to help others.
Attach personal project address: VUe-card-DIY welcome star~ ✨
What is the Fabric. The js?
Fabric.js is a powerful H5 Canvas framework that provides an interactive object model on top of the native Canvas, enabling rich manipulation on the canvas through a concise API.
The framework is an open source project at Github
What does fabric.js do?
With fabric.js, you can create and fill objects on the canvas; Such as simple geometric shapes — rectangles, circles, ovals, polygons, custom images or more complex shapes made up of hundreds or thousands of simple paths. In addition, you can scale, move, and rotate these objects with the mouse; Modify their attributes – color, transparency, Z-index, etc. You can also combine objects on the canvas. Below, I will introduce my common functions and scenarios. For more functions, please refer to the official documentation
The installation
NPM install
npm install fabric --save
Copy the code
Reference by CDN
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.min.js"></script>
Copy the code
Initialize the
First, write a canvas tag of 350 x 200 in the HTML page. It is ok to write no width and height here. Later, you can set the width and height through JS
<canvas id="canvas" width="350" height="200"></canvas>
Copy the code
Initialize the Canvas object of fabric to create a card.
const card = new fabric.Canvas('canvas')
/ /... Here you can write some configuration of the Canvas object, which will be described later
// If the
card.setWidth(350)
card.setHeight(200)
Copy the code
It’s as simple as that, and you’ve created a basic canvas.
Start pattern operation
Listen for events on the canvas
There are many official events, the following are commonly used events:
object:added
Add layerobject:modified
Edit the layerobject:removed
Remove the layerselection:created
First selected layerselection:updated
Layer selection changesselection:cleared
Clear layer select
// After the Canvas is initialized, listen in the following way
// For example, listen for the layer edit event on the canvas
card.on('object:modified', (e) => {
console.log(e.target) // e.target is the currently edited Object
/ /... Rotate, zoom, move, and so on
// So if there is an undo/restore scenario, here can save the edit state
});
Copy the code
Setting the canvas background
// Read the image address and set the canvas background
fabric.Image.fromURL('xx/xx/bg.jpg', (img) => {
img.set({
// Set the image size with scale, which is the same size as the canvas
scaleX: card.width / img.width,
scaleY: card.height / img.height,
});
// Set the background
card.setBackgroundImage(img, card.renderAll.bind(card));
card.renderAll();
});
Copy the code
If you want to set the background color of the canvas, you can set it when the canvas is initialized
const card = new fabric.Canvas('canvas', {
backgroundColor: 'blue' // Canvas background color is blue
});
/ / or
card.backgroundColor = 'blue';
/ / or
card.setBackgroundColor('blue');
Copy the code
Add a layer object to the canvas
Fabric.js provides many objects. In addition to the basic Rect, Circle, Line, Ellipse, Polygon, Polyline, Triangle objects, there are more advanced objects such as Image, Textbox, Group, etc. These are objects that inherit from Fabric.
Now I’m going to show you how to add images and text
/** * How do I add an Image object to the canvas? * /
// Method one (added via img element)
const imgElement = document.getElementById('my-image');
const imgInstance = new fabric.Image(imgElement, {
left: 100.// The left distance of the image relative to the canvas
top: 100.// The distance between the image and the top of the canvas
angle: 30.// Image rotation Angle
opacity: 0.85.// Image transparency
ScaleX and scaleY can be used to set the drawing size of the image. Here is half the original size
scaleX: 0.5.scaleY: 0.5
});
// Add the object as shown below
card.add(imgInstance);
Copy the code
// Method 2 (add by image path)
fabric.Image.fromURL('xx/xx/vue-logo.png', (img) => {
img.set({
hasControls: false.// Whether to enable layer controls
borderColor: 'orange'.// Layer control border color
});
// Add the object as shown below
canvas.add(img);
});
Copy the code
/** * How do I add a Textbox object to the canvas? * /
const textbox = new fabric.Textbox('This is a text.', {
left: 50.top: 50.width: 150.fontSize: 20.// Font size
fontWeight: 800.// Font size
// fill: 'red', // font color
// fontStyle: 'italic', // italic
// fontFamily: 'Delicious', // set font
// Stroke: 'green', // stroke color
// strokeWidth: 3, // strokeWidth
hasControls: false.borderColor: 'orange'.editingBorderColor: 'blue' // Click the text to enter the edit state of the border color
});
// Add the text as shown below
card.add(textbox);
Copy the code
Gets the currently selected layer object
/ / way
this.selectedObj = card.getActiveObject(); // Returns the selected layer in the current canvas
2 / / way
card.on('selection:created', (e) => {
// Dynamically update the assignment when the selected layer event is triggered
this.selectedObj = e.target
})
Copy the code
Rotate the layer
// Rotate clockwise 90°
const currAngle = this.selectedObj.angle; // Angle of the current layer
const angle = currAngle === 360 ? 90 :currAngle + 90;
this.selectedObj.rotate(angle);
// If the rotation is controlled by the slider
// this.selectedObj.rotate(slideValue);
// Call this method after all layer operations
card.renderAll()
Copy the code
Flip the layer
// Horizontal flip, vertical flip to scaleY property
this.selectedObj.set({
scaleX: -this.selectedObj.scaleX,
})
card.renderAll()
Copy the code
Remove the layer
card.remove(this.selectedObj) // Pass in the object to be removed
card.renderAll()
Copy the code
Controls layer levels on the canvas
Add layers to the canvas in ascending order by default, but when you select a layer to go active, the layer will be placed on the top layer by default.
// Set after the canvas is initialized
card.preserveObjectStacking = true // Disable layer customization on top when selected
Copy the code
After setting this, I selected the Vue logo to look like this, without topping it.
How do I move layers up and down?
// Move the layer up
this.selectedObj.bringForward();
// Move the layer down
this.selectedObj.sendBackwards();
// You can also move the layer to the specified position using the canvas object's moveTo method
card.moveTo(object, index);
Copy the code
Canvas state record
The framework provides methods such as toJSON and loadFromJSON, which export the JSON information of the current canvas and load the JSON canvas information to restore the state of the canvas.
// Export current canvas information
const currState = card.toJSON(); // The exported Json is shown in the following figure
Copy the code
// Load canvas information
card.loadFromJSON(lastState, () => {
card.renderAll();
});
Copy the code
Export the canvas as an image
const dataURL = card.toDataURL({
format: 'jpeg'./ / jpeg or PNG
quality: 0.8 // Image quality, jpeg only
// Intercepts the specified position and size
//left: 100,
//top: 100,
//width: 200,
//height: 200
});
Copy the code
So much for the basic introduction of fabric.js. The framework is very powerful and there are many other features to try out.
If reprinted this article please indicate the author and source!