場景
Fabricjs一個簡單強大的Canvas繪圖庫快速入門:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/122850075
在上面的基礎上,怎樣監聽畫布上鼠標按下、移動、抬起時的事件,以及畫布上對象
被選中、被移動、被旋轉、被加入和被移除的事件。

注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
1、畫布的事件監聽
//鼠標按下時事件 canvas.on('mouse:down', function(options) { console.log("mouse:down"+options.e.clientX, options.e.clientY) }) //鼠標移動時事件 canvas.on('mouse:move', function(options) { console.log("mouse:move"+options.e.clientX, options.e.clientY) }) //鼠標抬起時事件 canvas.on('mouse:up', function(options) { console.log("mouse:up"+options.e.clientX, options.e.clientY) })
2、對象的事件監聽
//繪制不規則圖形 var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z'); path.set({ left: 120, top: 120,fill:'red' }); //選中監聽事件 path.on('selected', function() { console.log('selected'); }); //對象移動監聽事件 path.on('moving', function() { console.log('moving'); }); //對象被旋轉監聽事件 path.on('rotating', function() { console.log('rotating'); }); //對象被加入監聽事件 path.on('added', function() { console.log('added'); }); //對象被移除監聽事件 path.on('removed', function() { console.log('removed'); });


3、完整示例代碼
<template>
<div>
<div>
<canvas id="c" width="800" height="800"></canvas>
</div>
</div>
</template>
<script>
import { fabric } from "fabric";
export default {
name: "HelloFabric",
data() {
return {};
},
mounted() {
this.init();
},
methods: {
init() {
// create a wrapper around native canvas element (with id="c")
// 聲明畫布
var canvas = new fabric.Canvas("c");
//鼠標按下時事件
canvas.on('mouse:down', function(options) {
console.log("mouse:down"+options.e.clientX, options.e.clientY)
})
//鼠標移動時事件
canvas.on('mouse:move', function(options) {
console.log("mouse:move"+options.e.clientX, options.e.clientY)
})
//鼠標抬起時事件
canvas.on('mouse:up', function(options) {
console.log("mouse:up"+options.e.clientX, options.e.clientY)
})
// create a rectangle object
// 繪制圖形
var rect = new fabric.Rect({
left: 80, //距離畫布左側的距離,單位是像素
top: 80, //距離畫布上邊的距離
fill: "red", //填充的顏色
width: 20, //方形的寬度
height: 20, //方形的高度
});
// "add" rectangle onto canvas
//添加圖形至畫布
canvas.add(rect);
//添加圖片
fabric.Image.fromURL('images/light.png', function(oImg) {
// scale image down, and flip it, before adding it onto canvas
//縮小圖像並翻轉它
oImg.scale(0.5).set('flipX', true);
canvas.add(oImg);
});
//繪制不規則圖形
var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z');
path.set({ left: 120, top: 120,fill:'red' });
//選中監聽事件
path.on('selected', function() {
console.log('selected');
});
//對象移動監聽事件
path.on('moving', function() {
console.log('moving');
});
//對象被旋轉監聽事件
path.on('rotating', function() {
console.log('rotating');
});
//對象被加入監聽事件
path.on('added', function() {
console.log('added');
});
//對象被移除監聽事件
path.on('removed', function() {
console.log('removed');
});
canvas.add(path);
},
},
};
</script>
