当前位置:网站首页>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;
});
边栏推荐
- jvm-对象生命周期
- Record 405 questions about bank callback post request
- 解决MySql 1045 Access denied for user ‘root‘@‘localhost‘ (using password: YES)
- Page generation QR code
- GoLand 2021.1.1: configure the multi line display of the tab of the open file
- 1px problem of mobile terminal
- Go language web development series 27: Gin framework: using gin swagger to implement interface documents
- Webpage connection database ~ simple implementation of addition, deletion, modification and query complete code
- Duet date picker (time plug-in that can manually enter the date)
- [技術發展-24]:現有物聯網通信技術特點
猜你喜欢
[email protected] Nanoparticles) | nano metal organic framework carry"/>
Metal organic framework material zif-8 containing curcumin( [email protected] Nanoparticles) | nano metal organic framework carry
可编程逻辑器件软件测试
QT learning 17 dialog box and its types
Generate directories from web content
Redis:Redis的数据结构、key的操作命令
RocksDB LRUCache
Redis:字符串類型數據的操作命令
小项目(servelt+jsp+mysql+EL+JSTL)完成一个登录功能的Servlet,具有增删改查的操作。实现登录身份验证,防止非法登录,防止多点登录,记住用户名密码功能。
Redis:字符串类型数据的操作命令
Use and design of Muduo buffer class
随机推荐
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
[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update
28: Chapter 3: develop Passport Service: 11: define attributes in the configuration file, and then obtain them in the code;
项目协作的进度如何推进| 社区征文
[Jilin University] information sharing of postgraduate entrance examination and re examination
Scroll detection, so that the content in the lower right corner is not displayed at the top of the page, but is displayed as the mouse slides
C language standard IO function sorting
Go language web development series 27: Gin framework: using gin swagger to implement interface documents
Folic acid modified metal organic framework (zif-8) baicalin loaded metal organic framework composite magnetic material (AU- [email
Go 1.16.4: manage third-party libraries with Mod
Installation impression notes
QT learning 23 layout manager (II)
Go language web development series 25: Gin framework: using MD5 to verify the signature for the interface station
Solve the problem of dormitory router campus network sharing login
MySQL data processing value addition, deletion and modification
“又土又穷”的草根高校,凭什么被称为“东北小清华”?
Uniapp skills - scrolling components -1
Richview trvstyle liststyle list style (bullet number)
Qt学习17 对话框及其类型
[combinatorics] permutation and combination (two counting principles, examples of set permutation | examples of set permutation and circle permutation)