Why won't my canvas clear between animation fr

2019-07-11 18:45发布

I decided to start playing around with dart again today and for some reason I can't get my viewport to clear between frames. I've tried to use clearRect and fillRect to draw a white rectangle over the entire canvas element. Here is my code.

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);


  }
}

The resulting animation draws a rectangle at the correct location but as it moves about the canvas the previous instance of the rectangle is still drawn. I'd like the rectangle to only appear once on the canvas and to look like it is moving about the screen.

Here is a screenshot of the output (notice the blue square is never cleared): Program Output

1条回答
该账号已被封号
2楼-- · 2019-07-11 19:26

I simplified your code to get it working:

In 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();
}

In Square:

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

I'm not sure what the exact problem was with the original version though. :)

查看更多
登录 后发表回答