【发布时间】:2018-02-22 10:38:03
【问题描述】:
我是 FabricJS 和 Typescript 的新手,试图在 Typescript/Angular 4 中的 Fabric JS 画布对象上实现类似对象的行为。我正在根据此处提供的 JavaScript 解决方案对我的代码进行建模:
https://stackoverflow.com/a/22649022/3207478
我遇到了以下错误:
this.canvas.getObjects().forEach(function (targ) { ...
每当移动对象时我从浏览器得到的错误是:
ERROR TypeError: Cannot read property 'getObjects' of undefined
at klass.<anonymous> (navigation.component.ts:72)
at klass.fire (fabric.js:239)
at klass._fire (fabric.js:10974)
at klass._performTransformAction (fabric.js:10963)
at klass._transformObject (fabric.js:10927)
at klass.__onMouseMove (fabric.js:10900)
at klass._onMouseMove (fabric.js:10520)
at ZoneDelegate.invokeTask (zone.js:367)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.invokeTask (zone.js:366)
at Zone.runTask (zone.js:166)
at HTMLDocument.ZoneTask.invoke (zone.js:420)
不确定在 Fabrics/@types 画布上遍历所有对象的最佳方式是在 TypeScript 中。 WebStorm IDE 建议将 getObjects 作为最有用的方法,但也许还有其他我没有看到的方法。
ngOnInit() {
// this.red = new fabric.Rect( {top: 100, left: 0, width: 80, height: 50, fill: 'red'});
// this.blue = new fabric.Rect( {top: 100, left: 0, width: 80, height: 50, fill: 'blue'});
// this.green = new fabric.Rect( {top: 100, left: 0, width: 80, height: 50, fill: 'green'});
this.canvas = new fabric.Canvas('canvas', { selection: true });
fabric.Object.prototype.transparentCorners = false;
this.canvas.on('object:moving', function (e) {
this.obj = e.target;
this.obj.setCoords(); // Sets corner position coordinates based on current angle, width and height
this.canvas.getObjects().forEach(function (targ) {
this.activeObject = this.canvas.getActiveObject();
if (targ === this.activeObject) { return; }
if (Math.abs(this.activeObject.oCoords.tr.x - targ.oCoords.tl.x) < this.edgedetection) {
this.activeObject.left = targ.left - this.activeObject.getWidth();
}
if (Math.abs(this.activeObject.oCoords.tl.x - targ.oCoords.tr.x) < this.edgedetection) {
this.activeObject.left = targ.left + targ.getWidth();
}
if (Math.abs(this.activeObject.oCoords.br.y - targ.oCoords.tr.y) < this.edgedetection) {
this.activeObject.top = targ.top - this.activeObject.getHeight();
}
if (Math.abs(targ.oCoords.br.y - this.activeObject.oCoords.tr.y) < this.edgedetection) {
this.activeObject.top = targ.top + targ.getHeight();
}
if (this.activeObject.intersectsWithObject(targ) && targ.intersectsWithObject(this.activeObject)) {
targ.strokeWidth = 10;
targ.stroke = 'red';
} else {
targ.strokeWidth = 0;
targ.stroke = false;
}
if (!this.activeObject.intersectsWithObject(targ)) {
this.activeObject.strokeWidth = 0;
this.activeObject.stroke = false;
}
});
});
}
【问题讨论】:
标签: typescript fabricjs