当前位置:网站首页>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 **
边栏推荐
- Operator details
- 创新永不止步——nVisual网络可视化平台针对Excel导入的创新历程
- Fabric.js 精简JSON
- Solution: the agent throws an exception error
- Find the subscript with and as the target from the array
- Cubemx DMA notes
- leetcode存在重复元素go实现
- Summary of MySQL key challenges (2)
- Fabric.js 激活输入框
- Gee: analyze the change of spatial centroid of remote sensing image [centroid acquisition analysis]
猜你喜欢

Using QA band and bit mask in Google Earth engine

Mathematical knowledge (Euler function)

Record my pytorch installation process and errors

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

Operator details

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

Nodejs (03) -- custom module

Gee series: Unit 4 data import and export in Google Earth engine

How to configure PostgreSQL 12.9 to allow remote connections

Simple and practical accounting software, so that accounts can be checked
随机推荐
Gee dataset: chirps pentad high resolution global grid rainfall dataset
National all Chinese Automatic Test Software apifox
设置滚动条默认样式 谷歌浏览器
Detailed explanation of Pointer use
Video multiple effects production, fade in effect and border background are added at the same time
Feign realizes file uploading and downloading
LeetCode 1175. Prime number arrangement (prime number judgment + Combinatorial Mathematics)
Go implements leetcode rotation array
Gee: create a new feature and set corresponding attributes
Foreign trade marketing website system development function case making
Mysql基础---查询(1天学会mysql基础)
Mathematical problems (number theory) trial division to judge prime numbers, decompose prime factors, and screen prime numbers
Global and Chinese market of impact roll 2022-2028: Research Report on technology, participants, trends, market size and share
Dark horse notes -- map set system
go实现leetcode旋转数组
Essence and physical meaning of convolution (deep and brief understanding)
线程池批量处理数据
LeetCode 241. Design priorities for operational expressions (divide and conquer / mnemonic recursion / dynamic programming)
Express logistics quick query method, set the unsigned doc No. to refresh and query automatically
Super detailed pycharm tutorial