当前位置:网站首页>Fabric. JS centered element
Fabric. JS centered element
2022-06-10 17:08:00 【Director of Moral Education Division】
In the use of Fabric.js When developing , You may need to center the element .
This article summarizes Fabric.js Common methods of centering elements , These include :
- Window based horizontal centering
- Canvas based horizontal centering
- Horizontal center with animation
- Window based vertical centering
- Canvas based vertical centering
- Vertical center with animation
- Horizontal and vertical centering at the same time ( It is also based on windows or canvas )
besides , It also sums up Center the specified element at the canvas level and The element itself calls the centered method .
Reading this article requires you to have some Fabric.js Basics , If you don't understand Fabric.js What is it? , You can read 《Fabric.js From entry to expansion 》
Create basic projects
For the convenience of demonstration , When I initialize the canvas :
- Add a background image , The size of the background image is as large as the initialized canvas .
- Add a rectangle , Then the object to be centered is it .
- Add mouse wheel to zoom canvas while scrolling ( Easy to demonstrate Based on windows and Canvas based The difference between ).
- Add mouse drag canvas translation position ( Easy to demonstrate Based on windows and Canvas based The difference between ).
<canvas id="canvasBox" width="600" height="600" style="border: 1px solid #ccc;"></canvas>
<!-- introduce Fabric.js -->
<script src="https://cdn.bootcdn.net/ajax/libs/fabric.js/521/fabric.js"></script>
<script>
// Initialize canvas
const canvas = new fabric.Canvas('canvasBox')
// Setting the background
fabric.Image.fromURL('../../images/bg2.jpg', img => {
canvas.setBackgroundImage(
img,
canvas.renderAll.bind(canvas),
{ // Set the width and height of the background image to the width and height of the canvas
scaleX: canvas.width / img.width,
scaleY: canvas.height / img.height
}
)
})
// Create a rectangle
const rect = new fabric.Rect({
name: 'rect',
top: 60, // From the top of the container 60px
left: 60, // To the left of the container 200px
fill: 'orange', // fill a Orange
width: 60, // Width 60px
height: 60, // Height 60px
originX: 'center',
originY: 'center'
})
// Add rectangle to canvas
canvas.add(rect)
// The zoom level of the canvas can be modified when the scroll wheel is scrolling
canvas.on('mouse:wheel', opt => {
const delta = opt.e.deltaY // Roller , Rolling up is -100, Rolling down is 100
let zoom = canvas.getZoom() // Gets the current zoom value of the canvas
zoom *= 0.999 ** delta
if (zoom > 20) zoom = 20
if (zoom < 0.01) zoom = 0.01
canvas.zoomToPoint(
{ // Key points
x: opt.e.offsetX,
y: opt.e.offsetY
},
zoom
)
})
/* Drag the canvas */
canvas.on('mouse:down', opt => { // Trigger when the mouse is pressed
let evt = opt.e
canvas.isDragging = true // isDragging Is custom
canvas.lastPosX = evt.clientX // lastPosX Is custom
canvas.lastPosY = evt.clientY // lastPosY Is custom
})
canvas.on('mouse:move', opt => { // Trigger when mouse moves
if (canvas.isDragging) {
let evt = opt.e
let vpt = canvas.viewportTransform // Focus view conversion
vpt[4] += evt.clientX - canvas.lastPosX
vpt[5] += evt.clientY - canvas.lastPosY
canvas.requestRenderAll()
canvas.lastPosX = evt.clientX
canvas.lastPosY = evt.clientY
}
})
canvas.on('mouse:up', opt => { // Trigger when the mouse is released
canvas.setViewportTransform(canvas.viewportTransform) // Set the viewport conversion for this canvas instance
canvas.isDragging = false
})
</script>
Copy code There's a bit more code , but The zoom level of the canvas can be modified when the scroll wheel is scrolling and Drag the canvas In fact, some of them are unnecessary , This code is mainly written for the convenience of demonstration .
All the elements referred to in the following examples are rect , Because this example takes rect Explain . You need to adjust according to the objects to be operated in the actual project .
Horizontal center
Center the specified element horizontally .
Based on windows
<button onclick="centerH()"> Horizontal center </button>
<script>
// Omitted code
// Horizontal center
function centerH() {
// Manipulate objects from the perspective of the canvas
canvas.viewportCenterObjectH(rect)
// The element itself is centered according to the window
// rect.viewportCenterH()
}
</script>
Copy code It says 2 Medium method , Method 1 Is to manipulate the specified object with the canvas ; Method 2 It is the element that adjusts its position according to the window .
Let me explain what is... Directly from the above figure Center the elements horizontally according to the window
Zoom
Moving the canvas
After zooming and moving the canvas ,canvas.viewportCenterObjectH and rect.viewportCenterH It will still be centered horizontally according to the standard of the window .
Canvas based
// Omitted code
canvas.centerObjectH(rect)
// The element itself is centered according to the canvas
// rect.centerH()
Copy code Zoom
Moving the canvas
You can talk to Based on windows Compare the effect of .
With animation effect
// Omitted code
canvas.fxCenterObjectH(rect)
Copy code The effect with animation needs to be called in the canvas fxCenterObjectH Method . The center with animation effect is centered according to the canvas , Not windows !
Vertical center
The usage of vertical center is similar to that of horizontal center , Just a change api. The horizontal center is “H” , For vertical centering “V”.
Based on windows
// Omitted code
canvas.viewportCenterObjectV(rect)
// The element itself is centered according to the window
// rect.viewportCenterV()
Copy code Canvas based
// Omitted code
canvas.centerObjectH(rect)
// The element itself is centered according to the canvas
// rect.centerH()
Copy code With animation
// Omitted code
canvas.fxCenterObjectV(rect)
Copy code level + vertical Center at the same time
Fabric.js It also provides the function of horizontal and vertical centering at the same time .
Based on windows
// Omitted code
canvas.viewportCenterObject(rect)
// The element itself is centered according to the window
// rect.viewportCenter()
Copy code Canvas based
// Omitted code
canvas.centerObject(rect)
// The element itself is centered according to the canvas
rect.center()
Copy code With animation
For the time being, we haven't found any animation effect in the vertical and horizontal center at the same time api, So you can try calling fxCenterObjectH and fxCenterObjectV
// Omitted code
function fxCenter() {
canvas.fxCenterObjectH(rect)
canvas.fxCenterObjectV(rect)
}
Copy code Code warehouse
边栏推荐
- 打造隐私计算领先方案 冲量在线数据互联平台获得鲲鹏Validated认证
- Fabric.js 精简输出的JSON
- 再联合 冲量在线与飞腾完成合作伙伴认证,携手打造信创隐私计算生态圈
- Desai wisdom number - words (text wall): 25 kinds of popular toys for the post-80s children
- ahk函数命令大全
- Example code of PHP for uploading multiple pictures
- What is the highest compound interest insurance product? How much does it cost a year?
- Then, we will cooperate with impulse online and Feiteng to complete partner certification and jointly create a private computing ecosystem for Xinchuang
- Rethinking atlas revolution for semantic image segmentation (deeplobv3) personal summary
- 圆周率 π 小数点第 100 万亿数字是多少?Google 用 Debian 服务器给出了答案
猜你喜欢

postman参数化

Shit, jialichuang's price is reduced again

解决idea打开某个项目卡住的问题

Take you to play completablefuture asynchronous programming

Intelligent scenic spot video monitoring 5g intelligent light pole gateway networking integrated pole

Hidden Markov model and its training (1)

What open source tools are actually used in the black cool monitoring interface?
![Download and install pycharm integrated development environment [picture]](/img/a1/a978f215517436c608f29a7d99c30c.jpg)
Download and install pycharm integrated development environment [picture]

Cannot locate a 64-bit Oracle Client library:The specified module could not be found.

MFC basic knowledge and course design ideas
随机推荐
Roll up and break through the anxiety of 35 years old. The animation demonstrates how easy it is for the CPU to record the function call process and enter the Internet factory
[web security self-study] section 1 building of basic Web Environment
Postman switching topics
互联网企业与芯片
Do you know the five GoLand shortcuts to improve efficiency?
PyTorch基础(一)-- Anaconda 和 PyTorch安装
Smart Scenic Spot Video Monitoring 5G Smart lamp Gateway Network Integrated pole
Institute of automation, Chinese Academy of Sciences: a review of the latest visual language pre training
Have you ever written a line of efficient code that equals 20 lines of others?
为 Chocolatey 设置代理
复利最高的保险产品是什么?一年要交多少钱?
Facebook AI | 从数百万预测结构中学习逆向折叠
解决idea打开某个项目卡住的问题
看先进科技如何改变人类生活
Enroulez - vous, brisez l'anxiété de 35 ans, l'animation montre le processeur enregistrer le processus d'appel de fonction, entrer dans l'usine d'interconnexion est si simple
postman参数化
“禁塑令”下,中宝新材深挖可降解塑料,港交所买单吗?
sql注入报错之注入原理实例解析
ASP. Net core 6 framework unveiling example demonstration [12]: advanced usage of diagnostic trace
VBA判断文件是否存在及问文件备份思路