1

我试图让angular2项目与hammerjs和fabricjs一起运行,但到目前为止没有运气。

我的 app.component.ts

    import { Component, OnInit } from '@angular/core';

declare var fabric: any;
let canvas: any;

    @Component({
      selector: 'ca-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      ngOnInit() {
    canvas = new fabric.Canvas('drawing_layer');
    const backImage = new Image();

    backImage.src = 'http://lorempixel.com/600/600/sports/';
    backImage.onload = () => {
      canvas.setBackgroundImage(backImage.src, canvas.renderAll.bind(canvas), {
        originX: 'left',
        originY: 'top',
        left: 0,
        top: 0,
      });

    };
  }
    }

canvas.on({
  'mouse:down': (ev) => {
    const pointer: any = canvas.getPointer(ev.e);
    const circle: any = new fabric.Circle({
      left: pointer.x,
      top: pointer.y,
      radius: 5,
      strokeWidth: 5,
      stroke: 'red',
      selectable: false,
      originX: 'center', originY: 'center',
    });

    canvas.add(circle);
  },
  'object:selected': (ev) => {
    console.info('object selected');
  },
  'selection:cleared': (ev) => {
console.info('selection cleared');
  },
});

let hammertime = new Hammer(document.getElementById("canvas-wrapper"));
hammertime.get("pinch").set({ enable: true });
hammertime.get("pan").set({ direction: Hammer.DIRECTION_ALL, threshold: 100 });
hammertime.on("pan", (ev) => {
    let fDeltaX: number;
    let fDeltaY: number;

    if (ev.pointerType === "mouse") {
        fDeltaX = ev.deltaX / 100;
        fDeltaY = ev.deltaY / 100;
    } else {
        fDeltaX = ev.deltaX / 10;
        fDeltaY = ev.deltaY / 10;
    }

    if (pageState.panning) {
        canvas.relativePan(new fabric.Point(Math.round(fDeltaX), Math.round(fDeltaY)));
    }
});
hammertime.on("pinch", (ev) => {
    canvas.setZoom(canvas.getZoom() * (ev.scale / 100));
});

我的 app.component.html

<div id="canvas-wrapper">
  <canvas id="drawing_layer"></canvas>
</div>

app.component.css

.upper-canvas {
  width: 100% !important;
  height: 100% !important;
}

目前它在“canvas.on”上抛出异常,目前还没有看到任何在线示例显示如何有效地使用 angular2 和fabricjs 和/或hammerjs。

4

1 回答 1

0

您应该将 canvas.on(){...} 放在 onInit 函数中。即,在组件初始化时,您“注册”您的回调,用于单击画布或您想要监视的任何其他事件。

于 2017-05-13T10:21:07.517 回答