fabricjs元素对齐方式实现
需求:
canvas 画布实现选中元素【左对齐】、【右对齐】、【顶对齐】、【底对齐】、【垂直居中对齐】、【水平居中对齐】
相关库及版本:
React(^18.2.0)、fabric(^5.2.4)
效果:





实现:
index.jsx
import React, { useEffect } from 'react';
import { fabric } from 'fabric';
import './index.less';
window.__cvs = null;
const Test = () => {
useEffect(() => {
// 初始化画布
window.__cvs = new fabric.Canvas('canvas', {
backgroundColor: '#fff',
width: 400,
height: 400,
});
// 添加三个不同颜色矩形元素
const rect1 = new fabric.Rect({
left: 100,
top: 100,
width: 70,
height: 70,
fill: '#E64B47',
});
const rect2 = new fabric.Rect({
left: 150,
top: 150,
width: 60,
height: 60,
fill: '#E1D184',
});
const rect3 = new fabric.Rect({
left: 200,
top: 200,
width: 50,
height: 50,
fill: '#895F41',
});
window.__cvs.add(rect1, rect2, rect3);
}, []);
return (
<div className="test">
<canvas id="canvas"></canvas>
<div className="btns">
<button
type="button"
onClick={() => {
const activeObjects = window.__cvs.getActiveObject();
activeObjects?._objects?.forEach((el) => {
const left = activeObjects.width / 2 - activeObjects.width;
el.set({
left,
});
});
window.__cvs.renderAll();
}}
>
左对齐
</button>
<button
type="button"
onClick={() => {
const activeObjects = window.__cvs.getActiveObject();
activeObjects?._objects?.forEach((el) => {
const left = activeObjects.width - el.width - activeObjects.width / 2;
el.set({
left,
});
});
window.__cvs.renderAll();
}}
>
右对齐
</button>
<button
type="button"
onClick={() => {
const activeObjects = window.__cvs.getActiveObject();
activeObjects?._objects?.forEach((el) => {
const top = activeObjects.height / 2 - activeObjects.height;
el.set({
top,
});
});
window.__cvs.renderAll();
}}
>
顶对齐
</button>
<button
type="button"
onClick={() => {
const activeObjects = window.__cvs.getActiveObject();
activeObjects?._objects?.forEach((el) => {
const top = activeObjects.height - el.height - activeObjects.height / 2;
el.set({
top,
});
});
window.__cvs.renderAll();
}}
>
底对齐
</button>
<button
type="button"
onClick={() => {
const activeObjects = window.__cvs.getActiveObject();
activeObjects?._objects?.forEach((el) => {
const left = (activeObjects.width - el.width) / 2 - activeObjects.width / 2;
el.set({
left,
});
});
window.__cvs.renderAll();
}}
>
垂直居中对齐
</button>
<button
type="button"
onClick={() => {
const activeObjects = window.__cvs.getActiveObject();
activeObjects?._objects?.forEach((el) => {
const top = (activeObjects.height - el.height) / 2 - activeObjects.height / 2;
el.set({
top,
});
});
window.__cvs.renderAll();
}}
>
水平居中对齐
</button>
</div>
</div>
);
};
export default Test;
index.less
.test { width: 100%; height: 100%; overflow-y: auto; .canvas-container { border: 1px solid #ddd; margin: 20px auto; } .btns { text-align: center; button { margin: 0 5px; } } }

浙公网安备 33010602011771号