import { useEffect, useState } from 'react' import * as fabric from 'fabric' import './App.css' function App() { const [count, setCount] = useState(0) // 获取Fabric.js版本号 const [fabricVersion] = useState(fabric.version) useEffect(() => { // 初始化画布 const canvas = new fabric.Canvas('game',{ // backgroundColor: 'rgb(100,100,200)', // 画布背景色(当前注释掉) selectionLineWidth: 2, // 多选框的边框宽度 selectionColor: 'rgba(0,255,0,0.3)', // 多选框的填充色(半透明绿色) selectionBorderColor: 'red', // 多选框的边框颜色 }); // 创建文本对象 const text = new fabric.Text('测试文字', { // 注意:正确类名是fabric.Text而非FabricText fontFamily: 'Comic Sans', // 字体类型 fontSize: 20, // 字体大小 underline: true, // 是否下划线 // fontWeight: 'bold', // 字体粗细(当前注释掉) shadow: 'rgba(0,0,0,0.3) 5px 5px 5px', // 文字阴影(颜色 x偏移 y偏移 模糊度) fill: 'blue', // 文字颜色 left: 100, // 文本左上角x坐标 top: 100 // 文本左上角y坐标 }); // 将文本添加到画布 canvas.add(text); // 定义多个矩形的配置参数 const rectConfigs = [ { left: 50, top: 50, width: 50, height: 50, stroke: 'red', angle: 0 }, { left: 250, top: 80, width: 200, height: 100, stroke: 'green', angle: 0 }, { left: 100, top: 90, width: 180, height: 180, stroke: 'blue', angle: 0 }, { left: 350, top: 200, width: 120, height: 100, stroke: 'yellow', angle: 0 } ]; // 循环创建并添加矩形到画布 rectConfigs.forEach(config => { const rect = new fabric.Rect({ ...config, // 解构配置参数(left/top/width/height/stroke/angle) fill: null, // 填充色(null表示透明) strokeWidth: 2, // 边框宽度 cornerColor: 'white', // 控制角点的填充色 cornerStrokeColor: 'blue', // 控制角点的边框色 borderColor: 'red', // 单个对象被选中时的边框颜色 cornerSize: 8, // 控制角点的大小(像素) cornerStyle: 'rect', // 控制角点的样式('rect'矩形/'circle'圆形) borderDashArray: [3, 3], // 边框虚线样式([实线长度, 间隙长度]) centeredRotation: true, // 旋转时是否以中心为原点 transparentCorners: false, // 控制角点是否透明(false为不透明) // hasBorders: false, // 是否显示选中边框(当前注释掉) // hasControls: false, // 是否显示控制角点(当前注释掉) }); // 为矩形添加选中事件监听 rect.on('selected', function(res) { console.log('选中了一个矩形', res); }); // 将矩形添加到画布 canvas.add(rect); }); // 为画布添加鼠标滚轮事件(实现缩放功能) canvas.on('mouse:wheel', function (opt) { var delta = opt.e.deltaY; // 滚轮滚动方向(正值向下,负值向上) var zoom = canvas.getZoom(); // 获取当前缩放比例 // 计算新的缩放比例(基于滚轮滚动距离) zoom *= 0.999 ** delta; // 限制缩放范围(最小0.01倍,最大20倍) if (zoom > 20) zoom = 20; if (zoom < 0.01) zoom = 0.01; // 设置新的缩放比例 canvas.setZoom(zoom); // 阻止事件冒泡和默认行为(避免页面滚动) opt.e.preventDefault(); opt.e.stopPropagation(); }); // 渲染画布(使所有添加的元素显示出来) canvas.renderAll(); // 组件卸载时清理画布资源 return () => { canvas.dispose(); }; }, []); return ( <> <h1>多个画框示例</h1> <div><canvas width="600" height="400" id="game"></canvas></div> <canvas id="step4" width="400" height="400"></canvas> <div className='card'> <button onClick={() => setCount((count) => count + 1)}>支持React: {count}</button> </div> <div>FabricJs Version: {fabricVersion} © 2024</div> </> ) } export default App
farbic
最新推荐文章于 2025-11-29 13:42:57 发布
1387

被折叠的 条评论
为什么被折叠?



