【发布时间】:2018-07-22 10:14:24
【问题描述】:
我做了一个包含两个函数的构造函数。其中一个update(),在update function 中有两个条件应该更新this.dx 或this.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;
}
<canvas id="canvas"></canvas>
【问题讨论】:
-
“构造函数不会更新对象值” 请发布您的问题,以便清楚您的问题是什么
-
我不清楚你在说什么,你能解释一下吗?
标签: javascript html canvas html5-canvas