Website-Suche

javascript - KineticJS-Form in TypeScript


Ich versuche, eine Form basierend auf dem folgenden kineticjs JavaScript-Code zu erstellen:

var triangle = new Kinetic.Shape({
    drawFunc: function(canvas) {
      var context = canvas.getContext();
      context.beginPath();
      context.moveTo(200, 50);
      context.lineTo(420, 80);
      context.quadraticCurveTo(300, 100, 260, 170);
      context.closePath();
      canvas.fillStroke(this);
    },
    fill: '#00D2FF',
    stroke: 'black',
    strokeWidth: 4
  });

Dies ist ein Beispiel, das zu finden ist unter: http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-shape-tutorial/

Mein TypeScript sieht so aus:

var square = new Kinetic.Shape({
        drawFunc: (canvas: any) => {
            var ctx = canvas.getContext();
            ctx.beginPath();
            ctx.moveTo(25, 25);
            ctx.lineTo(475, 25);
            ctx.lineTo(475, 475);
            ctx.lineTo(25, 475);
            ctx.closePath();
            canvas.fillStroke(this);
        },
        fill: '#FF0000',
    });

Der erzeugte JavaScript-Code sieht so aus:

var square = new Kinetic.Shape({
        drawFunc: function (canvas) {
            var ctx = canvas.getContext();
            ctx.beginPath();
            ctx.moveTo(25, 25);
            ctx.lineTo(475, 25);
            ctx.lineTo(475, 475);
            ctx.lineTo(25, 475);
            ctx.closePath();
            canvas.fillStroke(_this);
        },
        fill: '#FF0000'
    });

Das Problem tritt in der Zeile canvas.fillStroke(_this) auf. Das _this verweist auf meine Typescript-Klasse und nicht auf die generierte Form wie im JavaScript-Beispiel. Ich habe auch versucht, das canvas.fillStroke(this) in meinem Typescript durch () => canvas.fillStroke(this) zu ersetzen, aber das Ergebnis ist dasselbe.

Irgendwelche Ideen?

Antwort #1

Ich denke, du musst nur die Fat-Arrow-Notation vermeiden, die absichtlich den aktuellen Kontext von this als _this bewahrt.

Also sollte drawFunc: (canvas: any) => { drawFunc: function(canvas:any){ usw. sein.

Sieh hier den Unterschied: http://bit.ly/10cpdWw

Die Kommentare hier sind nützlich bezüglich _this und this: http://typescript.codeplex.com/workitem/248