当前位置:网站首页>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; // trueDraw 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;
});边栏推荐
- 解决MySql 1045 Access denied for user ‘root‘@‘localhost‘ (using password: YES)
- js . Find the first palindrome string in the array
- Implementation of Muduo accept connection, disconnection and sending data
- Common network state detection and analysis tools
- Go language unit test 4: go language uses gomonkey to test functions or methods
- [技術發展-24]:現有物聯網通信技術特點
- Windos creates Cordova prompt because running scripts is prohibited on this system
- Solve the problem of dormitory router campus network sharing login
- QT learning 20 standard dialog box in QT (middle)
- page owner特性浅析
猜你喜欢

Cross linked cyclodextrin metal organic framework loaded methotrexate slow-release particles | metal organic porous material uio-66 loaded with flavonoid glycosides | Qiyue
[email protected]纳米颗粒)|纳米金属有机框架搭载雷帕霉素|科研试剂"/>金属有机骨架材料ZIF-8包载姜黄素([email protected]纳米颗粒)|纳米金属有机框架搭载雷帕霉素|科研试剂

Rasp implementation of PHP

信创产业现状、分析与预测

QT learning 17 dialog box and its types
[email protected])|制备路线"/>叶酸修饰的金属-有机骨架(ZIF-8)载黄芩苷|金属有机骨架复合磁性材料([email protected])|制备路线

Qt学习20 Qt 中的标准对话框(中)

使用vscode查看Hex或UTF-8编码

JS first summary

MySQL data processing value addition, deletion and modification
随机推荐
Scroll detection of the navigation bar enables the navigation bar to slide and fix with no content
Generate directories from web content
JS first summary
Record 405 questions about bank callback post request
金属有机骨架材料ZIF-8包载姜黄素([email protected]纳米颗粒)|纳米金属有机框架搭载雷帕霉素|科研试剂
JS shift operators (< <,> > and > > >)
The small project (servlet+jsp+mysql+el+jstl) completes a servlet with login function, with the operation of adding, deleting, modifying and querying. Realize login authentication, prevent illegal log
Function calling convention
[技術發展-24]:現有物聯網通信技術特點
Thrift threadmanager and three monitors
Programmable logic device software testing
Go language web development series 28: solve cross domain access of CORS with gin contrib / CORS
Comprehensive case of MySQL data addition, deletion, modification and query
Formation of mil-100 (FE) coated small molecule aspirin [email protected] (FE) | glycyrrhetinic acid modified metal organ
金属有机骨架MIL-88负载阿霉素DOX|叶酸修饰UiO-66-NH2负载阿霉素[email protected]纳米粒子
MySQL 数据增删改查综合案例
金属有机骨架(MOFs)抗肿瘤药载体|PCN-223装载甲硝唑|UiO-66包载盐酸环丙沙星([email protected])
Webpage connection database ~ simple implementation of addition, deletion, modification and query complete code
全局事件总线
JVM class loading