fabric官网:
https://fabric5.fabricjs.com/demos/
创建画布并绘制
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fabric.js Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.2.4/fabric.min.js"></script>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="border: 1px solid #000;"></canvas>
<script>
const canvas = new fabric.Canvas('canvas');
// 添加矩形
const rect = new fabric.Rect({
left: 100,
top: 100,
width: 200,
height: 100,
fill: 'red',
stroke: 'black',
strokeWidth: 2,
});
canvas.add(rect);
// 添加文本
const text = new fabric.Text('Hello Fabric.js', {
left: 50,
top: 50,
fontSize: 30,
fill: 'green'
});
canvas.add(text);
// 监听对象选中事件
canvas.on('object:selected', function(e) {
console.log('对象被选中:', e.target);
});
</script>
</body>
</html>
canvas相关内容
canvas.on 是用于监听画布(Canvas)或画布上对象(Object)事件的方法。通过 canvas.on,你可以监听用户交互(如点击、拖拽、缩放等)或对象状态变化(如选中、移动、旋转等)的事件。
canvas.on('事件名称', 回调函数);
事件名称:要监听的事件名称,例如 ‘mouse:down’、‘object:selected’ 等。
回调函数:事件触发时执行的回调函数,通常接收一个事件对象 e 作为参数。
- 画布事件: mouse:down:鼠标在画布上按下时触发。 mouse:move:鼠标在画布上移动时触发。 mouse:up:鼠标在画布上释放时触发。 object:added:对象被添加到画布时触发。 object:removed:对象从画布中移除时触发。 - 对象事件: object:selected:对象被选中时触发。 object:moving:对象正在移动时触发。 object:scaling:对象正在缩放时触发。 object:rotating:对象正在旋转时触发。 object:modified:对象被修改(移动、缩放、旋转等)后触发。 - 选择事件: selection:created:创建选择(选中一个或多个对象)时触发。 selection:updated:选择更新时触发。 selection:cleared:选择被清除时触发。 - 在回调函数中,事件对象 e 通常包含以下常用属性: e.target:触发事件的对象(例如被选中的对象)。 e.pointer:鼠标的坐标({ x, y })。 e.button:鼠标按钮(左键、右键等)。 e.e:原生事件对象(如 MouseEvent)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fabric.js Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.2.4/fabric.min.js"></script>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="border: 1px solid #000;"></canvas>
<script>
const canvas = new fabric.Canvas('canvas');
// 添加矩形
const rect = new fabric.Rect({
left: 100,
top: 100,
width: 200,
height: 100,
fill: 'red',
stroke: 'black',
strokeWidth: 2,
});
canvas.add(rect);
// 监听画布点击事件
canvas.on('mouse:down', function (e) {
console.log('画布被点击,坐标:', e.pointer);
});
// 监听对象选中事件
canvas.on('object:selected', function (e) {
console.log('对象被选中:', e.target);
});
// 监听对象移动事件
canvas.on('object:moving', function (e) {
console.log('对象正在移动:', e.target);
});
// 监听选择事件
canvas.on('selection:created', function (e) {
console.log('选择被创建:', e.target);
});
canvas.on('selection:updated', function (e) {
console.log('选择被更新:', e.target);
});
canvas.on('selection:cleared', function (e) {
console.log('选择被清除');
});
</script>
</body>
</html>