首页 > 解决方案 > 为画布对象设置动画

问题描述

我做了一个包含两个函数的构造函数。其中之一update()update function有两个条件应该更新this.dxorthis.dy值,但它们没有更新值。

这是 JS Fiddle 链接:https ://jsfiddle.net/c9gnub14/

但是当我在构造函数之外(animate()函数内部)使用相同的条件时,它正在工作:https ://jsfiddle.net/b8h6j1vn/1/

实际上,我想为我的画布对象设置动画,你能告诉我这段代码有什么问题吗?

这是 JS Fiddle 链接:https : //jsfiddle.net/c9gnub14/ 请检查此代码段:

var canvas = document.getElementById('canvas'),
  c = canvas.getContext('2d')

canvas.width = window.innerWidth
canvas.height = window.innerHeight

function Circle(x, y, dx, dy, radius) {
  this.x = x
  this.y = y
  this.dx = dx
  this.dy = dy
  this.radius = radius

  this.draw = function() {
    c.beginPath()
    c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
    c.strokeStyle = 'blue'
    c.stroke()
  }

  this.update = function() {
    // ######################
    // dx & dy value is not updating with this code

    if (this.x + this.radius > innerWidth || this.x - this.radius < 0) {
      this.dx = -this.dx
      console.log('dx is ' + this.dx)
    }
    if (this.y + this.radius > innerHeight || this.y - this.radius < 0) {
      this.dy = -this.dy
      console.log('dy is ' + this.dx)
    }

    this.x += this.dx
    this.y += this.dy
    this.draw()
  }
}

var x = 200,
  y = 200,
  dx = 3,
  dy = 3,
  radius = 30

function animate() {
  requestAnimationFrame(animate)
  c.clearRect(0, 0, innerWidth, innerHeight)
  var circle = new Circle(x, y, dx, dy, radius)
  circle.update()

  // if (x + radius > innerWidth || x - radius < 0) {
  //     dx = -dx
  // }
  // if (y + radius > innerHeight || y - radius < 0) {
  //     dy = -dy
  // }

  // x += dx
  // y += dy
}

animate()
body {
  margin: 0;
}
<canvas id="canvas"></canvas>

标签: javascripthtmlcanvashtml5-canvas

解决方案


只需在 animate 函数之外调用此变量 var circle = new Circle(x, y, dx, dy, radius)

每次删除旧圈子并使用您的预定义值创建一个新圈子时,您都会在constructor function内部调用。animate functionanimate functionx, y, dx, dy and radius


推荐阅读