如何在fabric.js中实现调整形状大小时实时更新其尺寸
解决方案
步骤1:添加尺寸展示的页面容器
先在页面中新增用于展示尺寸的DOM元素,可自定义样式放在画布周边的固定位置:
<div id="sizeDisplay" style="position: fixed; top: 20px; right: 20px; padding: 8px 12px; background: #fff; border: 1px solid #eee; border-radius: 4px; display: none;"> 尺寸:<span id="widthVal">0</span> x <span id="heightVal">0</span> px </div>
步骤2:封装尺寸操作公共函数
// 更新显示的尺寸数值 function updateSizeDisplay(width, height) { const displayEl = document.getElementById('sizeDisplay') document.getElementById('widthVal').textContent = width document.getElementById('heightVal').textContent = height displayEl.style.display = 'block' } // 取消选中元素时隐藏尺寸提示 function hideSizeDisplay() { document.getElementById('sizeDisplay').style.display = 'none' }
步骤3:调整原有逻辑,新增事件监听
需要覆盖元素选中、尺寸修改、取消选中三个核心场景,修改后的完整代码如下:
// 全局监听元素选中事件,选中时直接展示当前元素尺寸 c.on('object:selected', function(options) { const target = options.target const width = Math.round(target.getWidth()) const height = Math.round(target.getHeight()) updateSizeDisplay(width, height) }) // 全局监听取消选中事件,取消选中时隐藏尺寸提示 c.on('selection:cleared', function() { hideSizeDisplay() }) function snapToGrid() { let checkBox = document.getElementById("myCheck"); if (checkBox.checked == true) { //snap only to the grid const gridSize = 50; c.on("object:moving", function (options) { options.target.set({ left: Math.round(options.target.left / gridSize) * gridSize, top: Math.round(options.target.top / gridSize) * gridSize, }); }); c.on("object:modified", function (options) { var newWidth = Math.round(options.target.getWidth() / gridSize) * gridSize; var newHeight = Math.round(options.target.getHeight() / gridSize) * gridSize; options.target.set({ width: newWidth, height: newHeight, scaleX: 1, scaleY: 1, }); // 尺寸修改完成后同步更新显示的数值 updateSizeDisplay(newWidth, newHeight) }); } else { c.off("object:modified"); c.off("object:moving"); // 关闭网格吸附后仍要监听尺寸修改事件,同步更新显示数值 c.on("object:modified", function (options) { const newWidth = Math.round(options.target.getWidth()) const newHeight = Math.round(options.target.getHeight()) updateSizeDisplay(newWidth, newHeight) }); } }
可选优化
如果需要在拖拽调整尺寸的过程中实时更新数值,不需要等拖拽结束再更新,把事件监听的object:modified替换为object:scaling即可。
内容的提问来源于stack exchange,提问作者Sheikha Hanna
相关产品推荐
相关产品推荐

