当前位置:网站首页>Fabric. JS document
Fabric. JS document
2022-07-03 14:08:00 【Cheat the old traditional Chinese medicine in the Jianghu】
Fabric.js It's one that can simplify Canvas The library of programming . Fabric.js by Canvas Provide the missing object model ,svg parser, Interaction and a whole set of other indispensable tools . because Fabric.js For foreign frameworks , official API Messy and numerous , Most of the relevant documents are in English , And the number is not much , So this article aims to help novices get started quickly in the project Fabric.js, Enjoy drawing Canvas The process of .
Why use Fabric.js?
Canvas Provide a good canvas ability , however Api Not friendly enough . Drawing simple graphics is actually OK , But do some complicated graphics , Write complex effects , It's not so convenient .Fabric.js Is developed for this , It is mainly to write code in the way of objects .
Fabric.js Something that can be done
- stay Canvas To create a 、 Fill in the figures ( Including pictures 、 written words 、 Regular graph and complex path constitute graph ).
- Fill the graphics with gradient colors .
- Combine graphics ( Including composite graphics 、 Graphic text 、 Pictures, etc ).
- Set up graphic animation set user interaction .
- Generate JSON, SVG Data etc. .
- Generate Canvas Object has drag and drop function .
start
Vue Introduced in the project Fabric.js
Suppose you are using ES6 and Webpack, You can start using Fabric.js, As shown below :
1、 On the command line :
npm install fabric( or yarn add fabric)2、 Introduce it .vue In file
import { fabric } from 'fabric'3、 stay .vue In the single file of mounted: Start your life cycle Fabric.js The trip
notes : default fabric npm The module produces a fairly large package , If Fabric.js There are many bags you may not need , under these circumstances , Can be in Here, Or build your own version on the command line .
Drawing graphics
Draw regular graphics
1、 Declaration canvas
var canvas =new fabric.Canvas('main');2、 Drawing graphics
var rect = new fabric.Rect({
left:100,// Distance from the left side of the canvas , Unit is pixel
top:100,// Distance from the top of the canvas
fill:'red',// Fill color
width:30,// The width of the square
height:30// The height of the square
});3、 Add graphics to canvas
canvas.add(rect);Other rule graphics :
- Draw a square
var rect = new fabric.Rect - Draw a circle
var circle = new fabric.Circle - Draw triangle
var triangle = new fabric.Triangle

Draw irregular figures
Use path drawing : Draw by moving points and lines . Through to Line 、 curve 、 The application of arc draws very complex graphics .
stay fabric.Path( ) In the method ,“M” representative “ Move ” command , This “M 00” Represents moving the brush to (0,0) Point coordinates .
“L” representative “ Line ”,“L 200 100 ” It means to draw a line with a pen , from (0,0) Coordinates drawn to (200,100) coordinate . “z” Represents the closed path of the graph .
After drawing the triangle , We can use set( ) Method for the position of the triangle 、 Color 、 angle 、 Transparency and other attributes .
The specific code is as follows :
var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z');
path.set({ left: 120, top: 120,fill:'red' });
canvas.add(path);
Operation of pictures
HTML Insert a picture
<body>
<canvas width='800' height='800'></canvas>
<img src="./2.png">
</body>
---------------------
var canvas = new fabric.Canvas('canvas');// Declaration canvas
var imgElement = document.getElementById('img');// Declare our pictures
var imgInstance = new fabric.Image(imgElement,{ // Set the position and appearance of the picture
left:100,
top:100,
width:200,
height:100,
angle:30// Set the clockwise rotation angle of the graph
});
canvas.add(imgInstance);// Add to canvas in 
JavaScript Insert a picture
var canvas = new fabric.Canvas('canvas');
fabric.Image.fromURL('./2.png', function(oImg) {
oImg.scale(0.1);// The picture shrinks 10 times
canvas.add(oImg);
}); Interaction
Interaction with canvas
canvas.add(imgInstance);// Add to canvas in
var canvas = new fabric.Canvas('canvas');
canvas.on('mouse:down', function(options) {
console.log(options.e.clientX, options.e.clientY)
})notes : Common monitoring events are as follows :
mouse:down: When the mouse is pressedmouse:move: When the mouse movesmouse:up: When the mouse is raised
Operations on objects on canvas
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({ width: 100, height: 50, fill: 'green' });
rect.on('selected', function() {// Select listen event
console.log('selected a rectangle');
});
var circle = new fabric.Circle({ radius: 75, fill: 'blue' });
circle.on('selected', function() {
console.log('selected a circle');
});
canvas.add(rect);
canvas.add(circle);notes : Common monitoring events are as follows :
after:render: After canvas redrawingobject:selected: Object is selectedobject:moving: Object movementobject:rotating: The object is rotatedobject:added: Objects are addedobject:removed: The object is removed

Combine
new fabric.Group(): Take two parameters : An array of object names to be combined 、 Common properties of objects grouped together .
var canvas = new fabric.Canvas('canvas');
var circle = new fabric.Circle({ // Draw a circle
radius: 100,
fill: '#f00',
scaleY: 0.5,
originX: 'center', // Adjust the center point X Axis coordinates
originY: 'center' // Adjust the center point Y Axis coordinates
});
var text = new fabric.Text('Hello World', { // Draw text
fontSize: 30,
originX: 'center',
originY: 'center'
})
// Are combined
var group = new fabric.Group([circle, text], {
left: 150,
top: 100,
angle: 10
})
canvas.add(group);
Serialization and deserialization
serialize
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
width: 100,
height: 100,
fill: 'red'
});
canvas.add(rect);
console.log(JSON.stringify(canvas.toJSON()));Deserialization
var canvas = new fabric.Canvas('canvas');
canvas.loadFromJSON('{"objects":[{"type":"rect","left":50,"top":50,"width":20,"height":20,"fill":"green","overlayFill":null}
]}')SVG
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
width: 100,
height: 100,
fill: 'red'
});
canvas.add(rect);
canvas.toSVG();fabric.js Use notes
object
fabric.Circle round
fabric.Ellipse The ellipse
fabric.Line A straight line
fabric.Polygon
fabric.Polyline
fabric.Rect rectangular
fabric.Triangle triangle
Method
add(object) add to
insertAt(object,index) add to
remove(object) remove
forEachObject Loop traversal
getObjects() Get all objects
item(int) Get children
isEmpty() Determine if the Sketchpad is empty
size() The number of Sketchpad elements
contains(object) Whether the query contains an element
fabric.util.cos
fabric.util.sin
fabric.util.drawDashedLine Draw a dotted line
getWidth() setWidth()
getHeight()
clear() Empty
renderAll() Repaint
requestRenderAll() Request re rendering
rendercanvas() Redraw Sketchpad
getCenter().top/left Get the center coordinates
toDatalessJSON() The sketchpad information is sequenced into the smallest json
toJSON() The sketchpad information is sequenced into json
moveTo(object,index) Move
dispose() Release
setCursor() Set gesture icons
getSelectionContext() Get the selected context
getSelectionElement() Get the selected element
getActiveObject() Get the selected object
getActiveObjects() Get multiple selected objects
discardActiveObject() Cancels the currently selected object
isType() The type of picture
setColor(color) = canvas.set("full","");
rotate() Set the rotation angle
setCoords() Set coordinates
event
object:added
object:removed
object:modified
object:rotating
object:scaling
object:moving
object:selected This method v2 Has been abandoned , Use selection:created replace , Multiple selection will not trigger
before:selection:cleared
selection:cleared
selection:updated
selection:created
path:created
mouse:down
mouse:move
mouse:up
mouse:over
mouse:out
mouse:dblclick
Common properties
canvas.isDrawingMode = true; You can draw freely
canvas.selectable = false; Control cannot be selected , Will not be operated
canvas.selection = true; The drawing board shows the selected
canvas.skipTargetFind = true; The entire palette element cannot be selected
canvas.freeDrawingBrush.color = "#E34F51" Set the color of the free paint pen
freeDrawingBrush.width Free stroke width
canvas.setZoom(2); Set the scale of the drawing board
IText Methods
selectAll() Choose all
getSelectedText() Get the selected text
exitEditing() Exit edit mode
Draw a straight line
var line = new fabric.Line([10, 10, 100, 100], {
fill: 'green',
stroke: 'green', // Stroke color
strokeWidth: 2,// Stroke width
});
canvas.add(line);Draw a dotted line
Add attributes on the basis of drawing lines strokeDashArray:Array
example:
var line = new fabric.Line([10, 10, 100, 100], {
fill: 'green',
stroke: 'green',
strokeDashArray:[3,1]
});
canvas.add(line);strokeDashArray[a,b] =》 every other a Pixels empty b Pixel .
Paintable objects
fabric.Circle round
fabric.Ellipse The ellipse
fabric.Line A straight line
fabric.Polygon
fabric.Polyline
fabric.Rect rectangular
fabric.Triangle triangle
Remove the selected border and rotate the picture , And can only move , Do not operate
oImg.hasControls = false; You can only move, you can't ( edit ) operation
oImg.hasBorders = false; Remove border , Can operate normally
hasRotatingPoint = false; Cannot be rotated
hasRotatingPoint The control rotation point is invisible
scaleToHeight(value, absolute) Zoom the image height to value scaleToWidth(value, absolute) Zoom the width of the picture to value
The sample code is as follows :
fabric.Image.fromURL("img.jpg", function (oImg) {
img.scaleToHeight(400, false); // Zoom the height of the picture to 400
img.scaleToWidth(400, false); // Zoom the width of the picture to 400
canvas.add(oImg);
oImg.hasControls = oImg.hasBorders = false;
});边栏推荐
- 可编程逻辑器件软件测试
- 解决MySql 1045 Access denied for user ‘root‘@‘localhost‘ (using password: YES)
- Simulated access
- Function calling convention
- Redis: commandes d'action pour les données de type chaîne
- Using registered classes to realize specific type matching function template
- Generate directories from web content
- Go language web development series 26: Gin framework: demonstrates the execution sequence of code when there are multiple middleware
- Why are grass-roots colleges and universities with "soil and poverty" called "Northeast small Tsinghua"?
- QT learning 23 layout manager (II)
猜你喜欢

QT learning 23 layout manager (II)

Golang - command line tool Cobra

How to use lxml to judge whether the website announcement is updated

Scroll detection of the navigation bar enables the navigation bar to slide and fix with no content

JS Part III

JS input number and standard digit number are compared. The problem of adding 0 to 0
[email protected])"/>金属有机骨架(MOFs)抗肿瘤药载体|PCN-223装载甲硝唑|UiO-66包载盐酸环丙沙星([email protected])

Spring cup eight school league

QT learning 25 layout manager (4)

Redis: commandes d'action pour les données de type chaîne
随机推荐
GoLand 2021.1: rename the go project
Page generation QR code
Cross linked cyclodextrin metal organic framework loaded methotrexate slow-release particles | metal organic porous material uio-66 loaded with flavonoid glycosides | Qiyue
Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:
Golang - command line tool Cobra
Go language unit test 4: go language uses gomonkey to test functions or methods
Print. JS -- web page file printing
信创产业现状、分析与预测
Article content typesetting and code highlighting
QT learning 22 layout manager (I)
How to use lxml to judge whether the website announcement is updated
How to promote the progress of project collaboration | community essay solicitation
TS code automatically generates JS
Metal organic framework (MOFs) antitumor drug carrier | pcn-223 loaded with metronidazole | uio-66 loaded with ciprofloxacin hydrochloride(
Uniapp skills - scrolling components -1
JS shift operators (< <,> > and > > >)
Common plug-ins for vite project development
28:第三章:开发通行证服务:11:在配置文件中定义属性,然后在代码中去获取;
Failure of vector insertion element iterator in STL
How to delete an attribute or method of an object