Canvas中的圆形任务问题

时间:2018-07-02 18:26:55

标签: javascript ecmascript-6 html5-canvas

我已经获得了以下任务,但是运行代码片段时却出现了一些错误。我需要一些帮助来弄清楚我到底在做什么错。

基本上,我需要画一个圆,使其顺着屏幕壁移动并改变方向/颜色。

  

任务:创建一个具有以下属性的Circle类:

     
      
  • x-坐标x的初始值
  •   
  • y是y坐标的初始值
  •   
  • 半径-宽度和高度的值
  •   
  • 颜色-填充颜色描述方法:
  •   
  • draw()-在屏幕上标记由给定属性描述的元素
  •   
  • setColor(newColor)-将填充颜色更改为newColor
  •   
  • 移动({x = 0,y = 0})-将捕获的对象移动向量(x,y)-每个时间段(例如100毫秒)变化(加\减)   分别设为x和y。当圆与任何一个碰撞时   屏幕边缘有必要实现其镜面反射   (更改矢量对应坐标的值   与符号值相反,并使用新的   向量)并生成碰撞事件,即碰撞,该事件被捕获   在文档级别。此事件将挂起一个将更改的处理程序   圆圈倒入另一个(随机)值的颜色。   移动会一直发生,直到调用stop方法为止。
  •   
  • 停止()-停止圆运动
  •   
     

如果按下了键盘上的Escape键,则移动应停止。

我创建了一个画布,并将框架设置为移动。我画了一个圆圈,并尝试使用setInterval()将其移动,但似乎丢失了上下文。

let c = document.getElementById("mycanvas");
let ctx = c.getContext("2d");

let xinc = 1;
let yinc = 1;

class Circle {
  constructor(xpos, ypos, radius, color) {
    this.xpos = xpos;
    this.ypos = ypos;
    this.radius = radius;
    this.color = color;
  }

  draw() {
    ctx.beginPath();
    ctx.arc(this.xpos, this.ypos, this.radius, 0, Math.PI * 2);
    ctx.fillStyle = "red";
    ctx.fill();
  }

  move(xpos, ypos) {
    ctx.clearRect(0, 0, c.width, c.height);
    ctx.beginPath();
    this.draw();

    xpos += xinc;
    ypos += yinc;
    console.log(xpos, ypos);
    if ((this.xpos > c.width - this.radius) || (this.xpos < 0 + this.radius)) {
      xinc = -xinc;
    }
    if ((this.ypos > c.height - this.radius) || (this.ypos < 0 + this.radius)) {
      yinc = -yinc;
    }
    setInterval(this.move, 10);
    //this.draw();
  }

}

let circle = new Circle(200, 300, 50, "red");
circle.draw();
circle.move(200, 300);
<canvas id="mycanvas" width="1335" height="650" style="border: 1px solid"> </canvas>

我才刚刚开始学习事件和DOM,请帮助我正确实现此任务

1 个答案:

答案 0 :(得分:0)

您正在将this.move传递到setInterval,而没有上下文-只是一个函数,没有this可以调用它。您可以传递this.move.bind(this)来创建< em> bound 函数。您也可以在构造函数this.move = this.move.bind(this)中完成一次。

此外,似乎不需要在beginPath中调用move