javascript - 为画布对象设置动画
问题描述
我做了一个包含两个函数的构造函数。其中之一update()
,update function
有两个条件应该更新this.dx
orthis.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>
解决方案
只需在 animate 函数之外调用此变量
var circle = new Circle(x, y, dx, dy, radius)
每次删除旧圈子并使用您的预定义值创建一个新圈子时,您都会在constructor function
内部调用。animate function
animate function
x, y, dx, dy and radius
推荐阅读
- arrays - 方程的点数组
- reactjs - 如何使 TextInput 中的 selectionColor 属性透明?
- amazon-web-services - 从 AWS 提取图像时,设备上没有剩余空间错误
- python - 函数'PyArray_DATA'的隐式声明
- php - 带有链接的消息并滚动到 Woocommerce 结帐详细信息
- infinispan - 缓存中的条目不会被驱逐
- c++ - '没有合适的转换函数'与 cout
- azure - 使用 Mongodb 和逻辑应用程序插入文档时出现问题
- java - 我将如何让这个程序接受扫描仪输入,直到我命令它停止接受它们
- python - 修改图形网格