2

今日もダーツをいじり始めることにしましたが、何らかの理由でフレーム間でビューポートをクリアできません。clearRect と fillRect を使用して、canvas 要素全体に白い四角形を描画しようとしました。これが私のコードです。

import 'dart:html';

void main() {

  var canvasFun = new CanvasFun(query("#Game"));

}

class CanvasFun{

  CanvasElement canvas;

  num _width;
  num _height;

  Square square;

  CanvasFun(this.canvas){
    this.square = new Square(10,10, new Point(50,50));
    requestRedraw();
  }

  void draw(num _){
    var ctx = canvas.context2d;

    //clear the viewport

    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);


    //draw the square
    this.square.draw(ctx);
    requestRedraw();

  }


  void requestRedraw() {
    window.requestAnimationFrame(draw);
  }

}
class Point {
  num x, y;

  Point(this.x, this.y);
}
class Square{
  num width;
  num height;

  num vectorX;
  num vectorY;

  Point location;

  Square(this.width, this.height, this.location){
    vectorX = 1;
    vectorY = 1;
  }

  void draw(CanvasRenderingContext2D context){
    context.save(); //I thought this might fix the blue viewport problem
    this.update(context);
    context.rect(this.location.x, this.location.y, this.width, this.height);
    context.fillStyle = "blue";
    context.fill();
  }
  void update(CanvasRenderingContext2D context)
  {
    num xBound = context.canvas.width;
    num yBound = context.canvas.height;

    if((this.location.x + this.width) > xBound){
      this.vectorX = -1;
    }
    else if(this.location.x < 0){
      this.vectorX = 1;
    }

    if((this.location.y + this.height) > yBound){
      this.vectorY = -1;
    }
    else if(this.location.y < 0){
      this.vectorY = 1;
    }

    this.location.x += (this.vectorX * 10);
    this.location.y += (this.vectorY * 20);


  }
}

結果として得られるアニメーションでは、正しい位置に長方形が描画されますが、キャンバス上を移動すると、長方形の前のインスタンスが引き続き描画されます。四角形がキャンバスに一度だけ表示され、画面上を移動しているように見えるようにしたいと思います。

出力のスクリーンショットを次に示します (青い四角がクリアされていないことに注意してください)。 プログラム出力

4

1 に答える 1

1

コードを簡略化して機能させました。

CanvasFun

void draw(num _){
    var ctx = canvas.context2d;

    //clear the viewport
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    //draw the square
    this.square.draw(ctx);
    requestRedraw();
}

Square

void draw(CanvasRenderingContext2D context){
    this.update(context);
    context.fillStyle = "blue";
    context.fillRect(this.location.x, this.location.y, this.width, this.height);
}

ただし、元のバージョンの正確な問題が何であったかはわかりません。:)

于 2013-02-06T14:40:39.853 に答える