当前位置:网站首页>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共享跨域的问题
- Fabric.js 激活输入框
- JS interview collection test question 1
- LS1046nfs挂载文件系统
- Leetcode 18 problem [sum of four numbers] recursive solution
- 在{{}}中拼接字符
- [opencv] image binarization
- Gee series: Unit 4 data import and export in Google Earth engine
- LeetCode 241. Design priorities for operational expressions (divide and conquer / mnemonic recursion / dynamic programming)
猜你喜欢

数据的储存

Gee data set: export the distribution and installed capacity of hydropower stations in the country to CSV table

CubeMx DMA笔记

Ansible installation and use

Gee: create a new feature and set corresponding attributes

C case of communication between server and client based on mqttnet

函数栈帧的创建和销毁

Mathematical problems (number theory) trial division to judge prime numbers, decompose prime factors, and screen prime numbers

Fabric.js IText设置指定文字的颜色和背景色

Fabric.js 激活输入框
随机推荐
Collectors.groupingBy 排序
Save the CDA from the disc to the computer
数据库问题汇总
Map in JS (including leetcode examples)
Online English teaching app open source platform (customized)
Exercise notes 13 (effective letter ectopic words)
Essence and physical meaning of convolution (deep and brief understanding)
国产全中文-自动化测试软件Apifox
Fabric.js 居中元素
函数栈帧的创建和销毁
Fabric.js 更换图片的3种方法(包括更换分组内的图片,以及存在缓存的情况)
Fabric.js 3个api设置画布宽高
Express logistics quick query method, set the unsigned doc No. to refresh and query automatically
paddle: ValueError:quality setting only supported for ‘jpeg‘ compression
【pyinstaller】_get_sysconfigdata_name() missing 1 required positional argument: ‘check_exists‘
Pyflink writes MySQL examples with JDBC
Fabric.js 将本地图像上传到画布背景
Draw a wave chart_ Digital IC
Fasttext text text classification
在{{}}中拼接字符