当前位置:网站首页>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.jsHow 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.js4.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.minMethod ). - 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.minMethod ). - 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 **
边栏推荐
- php/js cookie共享跨域的问题
- Operator details
- 7.TCP的十一种状态集
- Gee dataset: chirps pentad high resolution global grid rainfall dataset
- 创新永不止步——nVisual网络可视化平台针对Excel导入的创新历程
- Differential identities (help find mean, variance, and other moments)
- Fasttext text text classification
- Go implements leetcode rotation array
- Super detailed pycharm tutorial
- Find the subscript with and as the target from the array
猜你喜欢

Gee series: Unit 3 raster remote sensing image band characteristics and rendering visualization

视差特效的原理和实现方法

Detailed explanation of Pointer use

LeetCode 241. 为运算表达式设计优先级(分治/记忆化递归/动态规划)

Disable access to external entities in XML parsing

Pyechart1.19 national air quality exhibition

Express logistics quick query method, set the unsigned doc No. to refresh and query automatically

Collectors. Groupingby sort
![Gee: use of common mask functions in remote sensing image processing [updatemask]](/img/55/bf4ef5fc923242e72caab71f1a4e4b.jpg)
Gee: use of common mask functions in remote sensing image processing [updatemask]

paddle: ValueError:quality setting only supported for ‘jpeg‘ compression
随机推荐
Fabric.js 3个api设置画布宽高
Gee: analyze the change of spatial centroid of remote sensing image [centroid acquisition analysis]
Gee series: Unit 4 data import and export in Google Earth engine
Cubemx DMA notes
Fasttext text text classification
Fabric.js 将本地图像上传到画布背景
Fabric.js 右键菜单
Fabric.js 更换图片的3种方法(包括更换分组内的图片,以及存在缓存的情况)
C# 图片显示占用问题
CubeMx DMA笔记
Mapping settings in elk (8) es
Mysql重点难题(2)汇总
Global and Chinese market of cell culture freezers 2022-2028: Research Report on technology, participants, trends, market size and share
Go GC garbage collection notes (three color mark)
Fabric.js 激活输入框
Global and Chinese markets for marine selective catalytic reduction systems 2022-2028: Research Report on technology, participants, trends, market size and share
4. Flask cooperates with a tag to link internal routes
Gee series: unit 6 building various remote sensing indexes in Google Earth engine
Draw a wave chart_ Digital IC
Fabric.js 背景不受视口变换影响