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');
// 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>