背景:
想在对象中添加自定义控件,做某些特定操作,例如点击图标复制,新建等
第一步:创建图标对象
//图标属性与点击的回调函数
textObj:{
x: 0.5,
y: 0,
offsetY: -16,
offsetX: 16,
handlerFunction:function(eventData, transform) { //绑定事件
}
}
iconCallback:function(image, iconName, obj) {
const _this=this
fabric.Object.prototype.controls[iconName] = new fabric.Control({
x: obj.x,
y: obj.y,
offsetY: obj.offsetY,
offsetX: obj.offsetX,
cornerSize: obj.size,
cursorStyle: "pointer",
mouseUpHandler: obj.handlerFunction,
render: _this.renderIcon(image._element, 0),
});
},
renderIcon:function(image, initialAngle) {
return function (ctx, left, top, styleOverride, fabricObject) {
let size = this.cornerSize;
ctx.save();
ctx.translate(left, top);
ctx.rotate(
fabric.util.degreesToRadians(fabricObject.angle + initialAngle)
);
ctx.drawImage(image, -size / 2, -size / 2, size, size);
ctx.restore();
};
},
// 创建图标
const _this=this
fabric.Image.fromURL(
require("../assets/tianjiawenzi.svg"), //你的图标路径
function (image) {
_this.iconCallback(image, "textControl", _this.textObj);
}
);