【问题标题】:Animate the canvas object为画布对象设置动画
【发布时间】:2018-07-22 10:14:24
【问题描述】:

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

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

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

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

这里是 JS Fiddle 链接:https://jsfiddle.net/c9gnub14/ 请检查这个sn-p:

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;
}
&lt;canvas id="canvas"&gt;&lt;/canvas&gt;

【问题讨论】:

  • “构造函数不会更新对象值” 请发布您的问题,以便清楚您的问题是什么
  • 我不清楚你在说什么,你能解释一下吗?

标签: javascript html canvas html5-canvas


【解决方案1】:

更新函数应该更新 this.dx 或 this.dy 的值,但它没有更新值,

根据您编写的逻辑,如果圆圈不在屏幕上,它会更新这些值。但它不在屏幕外。中心点是200200,半径是30,所以它从170到230,已经在屏幕上,所以dx和dy都不会改变。

【讨论】:

  • 我只是禁用了this.update 中的条件并在构造函数之外使用相同的条件,现在动画正在工作。请检查:jsfiddle.net/b8h6j1vn
【解决方案2】:

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

每次animate function 都在animate function 中调用constructor function,删除旧圈子并使用预定义的x, y, dx, dy and radius 值创建一个新圈子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多