当前位置:网站首页>Canvas utility library fabric JS user manual
Canvas utility library fabric JS user manual
2022-07-03 14:08:00 【Cheat the old traditional Chinese medicine in the Jianghu】
Introduction what is Fabric.js?
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);
Fabric Provides 7 Basic object classes in , If you just draw these figures , It will save us a lot of time :
- fabric.Circle // circular
- fabric.Ellipse // The ellipse
- fabric.Line // Line
- fabric.Polygon // polygon
- fabric.Polyline // Cross line Broken line
- fabric.Rect // rectangular
- fabric.Triangle// triangle
These instances inherit fabric.Object, If you want to draw some figures , And need some public methods . Then you can fabric.Object Define a method on , Let subclasses continue .
For example, we set a method getAngleInRadians Method in fabric.Object On the object :
fabric.Object.prototype.getAngleInRadians = function() {
return this.get('angle') / 180 * Math.PI;
};
var rect = new fabric.Rect({ angle: 45 });
rect.getAngleInRadians(); // 0.785...
var circle = new fabric.Circle({ angle: 30, radius: 10 });
circle.getAngleInRadians(); // 0.523...
circle instanceof fabric.Circle; // true
circle instanceof fabric.Object; // true
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 id="canvas" width='800' height='800'></canvas>
<img src="./2.png" id="img">
</body>
---------------------
<script>
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
</script>
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;
});
边栏推荐
- Leetcode-1175. Prime Arrangements
- Common mixins
- Go 1.16.4: manage third-party libraries with Mod
- Qt学习24 布局管理器(三)
- Golang — template
- Metal organic framework (MOFs) antitumor drug carrier | pcn-223 loaded with metronidazole | uio-66 loaded with ciprofloxacin hydrochloride( Redis: commandes d'action pour les données de type chaîne
- Common network state detection and analysis tools
- Redis:字符串类型数据的操作命令
- 【吉林大学】考研初试复试资料分享
猜你喜欢
可编程逻辑器件软件测试
RocksDB LRUCache
Configure stylelint
28: Chapter 3: develop Passport Service: 11: define attributes in the configuration file, and then obtain them in the code;
Article content typesetting and code highlighting
Conversion function and explicit
交联环糊精金属有机骨架负载甲氨蝶呤缓释微粒|金属-有机多孔材料UiO-66负载黄酮苷类药物|齐岳
Multi person collaborative data annotation based on Baidu brain easydata from scratch
Qt学习23 布局管理器(二)
使用vscode查看Hex或UTF-8编码
随机推荐
[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update
Summary of common error reporting problems and positioning methods of thrift
Qt学习21 Qt 中的标准对话框(下)
Qt学习17 对话框及其类型
QT learning 19 standard dialog box in QT (top)
28: Chapter 3: develop Passport Service: 11: define attributes in the configuration file, and then obtain them in the code;
Nucleic acid modified metal organic framework drug carrier | pcn-223 metal organic framework encapsulated ad adamantane | zif-8 encapsulated adriamycin (DOX)
Redis:Redis的数据结构、key的操作命令
金属有机骨架MIL-88负载阿霉素DOX|叶酸修饰UiO-66-NH2负载阿霉素[email protected]纳米粒子
[acnoi2022] guess numbers
UiO-66-COOH装载苯达莫司汀|羟基磷灰石( HA) 包裹MIL-53(Fe)纳米粒子|装载黄芩苷锰基金属有机骨架材料
Scroll detection of the navigation bar enables the navigation bar to slide and fix with no content
28:第三章:开发通行证服务:11:在配置文件中定义属性,然后在代码中去获取;
Screenshot of the operation steps of upload labs level 4-level 9
How to delete an attribute or method of an object
“又土又穷”的草根高校,凭什么被称为“东北小清华”?
Message subscription and publishing
JS first summary
Metal organic framework MOFs loaded with non steroidal anti-inflammatory drugs | zif-8 wrapped Prussian blue loaded quercetin (preparation method)
QT learning 20 standard dialog box in QT (middle)