当前位置:网站首页>Fabric. JS free draw rectangle
Fabric. JS free draw rectangle
2022-07-02 05:17:00 【Director of Moral Education Department】
Want to know more Fabric.js
How to play , Pay attention to me , Get the latest push at the first time
<br>
<br>
Brief introduction
Before reading this article , The first thing you need to know is
Fabric.js
, Also need to knowFabric.js
How to create a rectangle .If you haven't met the above 2 Conditions , Recommended reading 《Fabric.js From the beginning to ____》
<br>
I am here Fabric.js
Use Box selection operation Create a rectangle .
In the next few articles, I will write how to draw freely circular 、 ellipse 、 triangle 、 Line segment 、 Broken line 、 polygon .
<br>
This article does not do any CSS
Related beautification , Just explain the implementation principle .
The following figure is the effect to be achieved in this paper .
<br>
Use Fabric.js
Such framework , Pay attention to the version .
Version used in this article :
Fabric.js
4.6.0
<br>
<br>
principle
The core principle
use “ Frame selection ” To generate a rectangle , Its core is 2 spot :
- mouse Click on and lift Get coordinate points when , That is to say The starting point and The end point .
- When the mouse is raised , The first 1 spot Acquired 2 Calculate the length of the rectangle with three coordinates 、 Width and position .
<br>
Mouse click :canvas.on('mouse:down', fn)
The mouse is raised : canvas.on('mouse:up', fn)
<br>
Factors to consider
Understand the core points above , The next thing to consider is the selection of the mouse box Direction .
- from Top left Go to The lower right Frame selection
- from The lower right Go to Top left Frame selection
- from The lower left Go to The upper right Frame selection
- from The upper right Go to The lower left Frame selection
<br>
The above 4 This situation will affect the shape of the generated rectangle Long 、 wide and Location .
<br>
Code for generating rectangle
new fabric.Rect({ top: 0, // The upper left corner of the rectangle is y Position of the shaft left: 0, // The upper left corner of the rectangle is x Position of the shaft width: 100, // The width of the rectangle height: 100, // The height of the rectangle fill: 'transparent', // Fill color stroke: '#000' // Border color })
<br>
Let's talk about this one by one 4 The impact of these operations .
<br>
from Top left Go to The lower right Frame selection
This situation is best handled .
here The starting point It's the upper left corner of the rectangle , The end point It's the lower right corner of the rectangle .
The starting point Of x and y coordinate
All less than The end point ,( The starting point x < The end point x; The starting point y < The end point y ) :
- The width of the rectangle :
The end point x coordinate - The starting point x coordinate
( You could say( The starting point x - The end point x) The absolute value of
). - The height of the rectangle :
The end point y coordinate - The starting point y coordinate
( You could say( The starting point y - The end point y) The absolute value of
). - The upper left corner is x Position of the shaft :
Starting point x Axis coordinates
. - The upper left corner is y Position of the shaft :
Starting point y Axis coordinates
.
<br>
from The lower right Go to Top left Frame selection
The starting point x > The end point x; The starting point y > The end point y
- wide :
The starting point x - The end point x
. - high :
The starting point y - The end point y
. - The upper left corner is x Axis coordinates :
The end point x
- The upper left corner is y Axis coordinates :
The end point y
<br>
from The lower left Go to The upper right Frame selection
The starting point x < The end point x; The starting point y > The end point y
- wide :
( The starting point x - The end point y) The absolute value of
- high :
The starting point y - The end point y
- The upper left corner is x Axis coordinates :
The starting point x
( Compare x coordinate , Take the smaller one , It can be usedMath.min
Method ). - The upper left corner is y Axis coordinates :
The end point y
( Compare y coordinate , Take the smaller one ).
<br>
from The upper right Go to The lower left Frame selection
The starting point x > The end point x; The starting point y < The end point y
- wide :
The starting point x - The end point x
. - high :
( The starting point y - The end point y) The absolute value of
. - The upper left corner is x Axis coordinates :
The end point x
( Compare x coordinate , Take the smaller one , It can be usedMath.min
Method ). - The upper left corner is y Axis coordinates :
The starting point y
( Compare y coordinate , Take the smaller one ).
<br>
Sum up the formula
After analyzing the above 4 In this case , Finally, the formulas of these parameters are summarized .
I will The starting point Name it downPoint
, The end point Name it upPoint
.
Several parameters of rectangle are calculated as follows :
new fabric.Rect({ top: Math.min(downPoint.y, upPoint.y), left: Math.min(downPoint.x, upPoint.x), width: Math.abs(downPoint.x - upPoint.x), height: Math.abs(downPoint.y - upPoint.y), fill: 'transparent', stroke: '#000'})
<br>
Math.min
: Whichever is less
Math.abs
: Return the absolute value
These are both JS
Methods provided , If you don't understand my suggestion, go to Baidu .
<br>
<br>
Do it
I post it here for The original way Implementation code and comments .
If you want to know Vue3
How to achieve Fabric.js Draw a rectangle freely
, Can be in Code warehouse Search in .
<!-- The toolbar --><div class="toolbar"> <select onchange="typeChange(this.options[this.options.selectedIndex].value)"> <option value="default"> Default ( Frame selection )</option> <option value="rect"> rectangular </option> </select></div><!-- canvas --><canvas id="canvas" width="800" height="800"></canvas><!-- introduce fabric.js --><script src="https://cdn.bootcdn.net/ajax/libs/fabric.js/460/fabric.js"></script><script>let canvas = null // Canvas object let currentType = 'default' // Current operating mode ( Default || Create a rectangle )let downPoint = null // Coordinates when pressing the mouse let upPoint = null // Coordinates when releasing the mouse // Initialize Sketchpad function initCanvas() { canvas = new fabric.Canvas('canvas') canvas.on('mouse:down', canvasMouseDown) // Press the mouse on the canvas canvas.on('mouse:up', canvasMouseUp) // Release the mouse on the canvas }// Canvas operation type switching function typeChange(opt) { currentType = opt switch(opt) { case 'default': // Default box selection mode canvas.selection = true // Allow box selection canvas.selectionColor = 'rgba(100, 100, 255, 0.3)' // Check box fill color : Translucent blue canvas.selectionBorderColor = 'rgba(255, 255, 255, 0.3)' // Check box border color : Translucent gray canvas.skipTargetFind = false // Allow selection break case 'rect': // Create a rectangular pattern canvas.selectionColor = 'transparent' // Check box fill color : transparent canvas.selectionBorderColor = 'rgba(0, 0, 0, 0.2)' // Check box border color : Black with low transparency ( It looks gray ) canvas.skipTargetFind = true // Do not select break }}// Press the mouse on the canvas function canvasMouseDown(e) { // When the left mouse button is pressed , Set the current coordinates Assign a value to downPoint.{x: xxx, y: xxx} The format of downPoint = e.absolutePointer}// Release the mouse on the canvas function canvasMouseUp(e) { // Draw rectangle mode , Just execute the following code if (currentType === 'rect') { // When you release the left mouse button , Set the current coordinates Assign a value to upPoint upPoint = e.absolutePointer // call Create a rectangle Methods createRect() }}// Create a rectangle function createRect() { // If you click and release the mouse , All at the same coordinate point , No rectangle will be generated if (JSON.stringify(downPoint) === JSON.stringify(upPoint)) { return } // Create a rectangle // Rectangular parameter calculation ( As summarized above 4 Formula ) let top = Math.min(downPoint.y, upPoint.y) let left = Math.min(downPoint.x, upPoint.x) let width = Math.abs(downPoint.x - upPoint.x) let height = Math.abs(downPoint.y - upPoint.y) // Rectangular objects const rect = new fabric.Rect({ top, left, width, height, fill: 'transparent', // Fill color : transparent stroke: '#000' // Border color : black }) // Add a rectangle to the canvas canvas.add(rect) // After creating the rectangle , Empty downPoint and upPoint. Of course , You can also skip this step . downPoint = null upPoint = null}// The life cycle of page loading , Execute here Initialize canvas The operation of window.onload = function() { initCanvas()}</script>
<br>
<br>
Code warehouse
<br>
<br>
Recommended reading
<br> ** give the thumbs-up + Focus on + Collection = Learned to **
边栏推荐
- 4. Flask cooperates with a tag to link internal routes
- Implementation of go language for deleting duplicate items in sorting array
- 7.1模擬賽總結
- Go GC garbage collection notes (three color mark)
- C case of communication between server and client based on mqttnet
- 删除排序数组中的重复项go语言实现
- Fabric.js 精简JSON
- Gee dataset: chirps pentad high resolution global grid rainfall dataset
- 7.1模拟赛总结
- fastText文本分类
猜你喜欢
Fabric.js 精简JSON
Collectors. Groupingby sort
Gee: remote sensing image composite and mosaic
运维工作的“本手、妙手、俗手”
How to configure PostgreSQL 12.9 to allow remote connections
No logic is executed after the El form is validated successfully
Express logistics quick query method, set the unsigned doc No. to refresh and query automatically
Go Chan's underlying principles
Solution: the agent throws an exception error
[opencv] image binarization
随机推荐
Gee: use of common mask functions in remote sensing image processing [updatemask]
Global and Chinese market of impact roll 2022-2028: Research Report on technology, participants, trends, market size and share
数据库批量插入数据
Fabric.js 将本地图像上传到画布背景
LeetCode 241. 为运算表达式设计优先级(分治/记忆化递归/动态规划)
Feign realizes file uploading and downloading
Fabric.js 基础笔刷
Here comes the chicken soup! Keep this quick guide for data analysts
7.1 simulation summary
Express logistics quick query method, set the unsigned doc No. to refresh and query automatically
线程池批量处理数据
7.1模擬賽總結
C# 图片显示占用问题
Fabric.js 更换图片的3种方法(包括更换分组内的图片,以及存在缓存的情况)
Johnson–Lindenstrauss Lemma(2)
Preparation for writing SAP ui5 applications using typescript
Global and Chinese markets of semiconductor laser therapeutics 2022-2028: Research Report on technology, participants, trends, market size and share
Thread pool batch processing data
Mathematical knowledge -- understanding and examples of fast power
el form 表单validate成功后没有执行逻辑