在尝试学习javascript对象时,我想我会编写一个简单的程序,然后将其转换为基于对象的代码。我不确定我哪里出错了。继承了原始代码:
<!DOCTYPE html>
<html>
<head>
<style>
#canvas { background: #ddd; border:5px black ridge; }
</style>
<script>
function start() {
var ctx = document.getElementById('canvas').getContext('2d');
var angle = 163;
var radians = angle * Math.PI / 180;
var speedX = 1.5, speedY = 0.05, x = 0, y = 100;
draw();
function draw() {
x += speedX;
angle += speedY;
y += Math.sin(angle) * radians;
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.beginPath();
ctx.arc(x, y, 50, 0, Math.PI * 2, false);
ctx.fill();
document.getElementById('test').innerHTML = y;
requestAnimationFrame(draw);
}
}
window.addEventListener("load", start);
</script>
</head>
<body>
<canvas id="canvas" width="1000" height="300"></canvas>
<h2 id="test"></h2>
</body>
</html>
和heres到目前为止我用对象得到了什么:
<!DOCTYPE html>
<html>
<head>
<style>
#canvas { background: #ddd; border:5px black ridge; }
</style>
<script>
function start() {
var ctx = document.getElementById('canvas').getContext('2d');
var cW = ctx.canvas.width, cH = ctx.canvas.height;
var enemy = {
_x: 1,
_y: 10,
create: function(x, y, xv, range) {
var obj = Object.create(this);
obj.setX(x);
obj.setY(y);
obj.speedX(xv);
obj.ySin(range);
return obj;
},
setX: function(value) {
this._x = value;
},
setY: function(value) {
this._y = value;
},
getX: function() {
return this._x;
},
getY: function() {
return this._y;
},
speedX: function(spd) {
this._x += spd;
},
ySin: function(rangeOfAngle) {
var radians = rangeOfAngle * Math.PI / 180;
rangeOfAngle += 0.05;
this._y += Math.sin(rangeOfAngle) * radians;
return this._y;
},
addTo: function(v2) {
this._x += v2.getX();
this._y += v2.getY();
},
update: function() {
this.speedX(1.5);
this.ySin(this._y);
}
};
var p = enemy.create(0, 100, 1, 10);
render();
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(p.getX(), p.getY(), 30, 0, Math.PI * 2, false);
p.update();
ctx.fill();
document.getElementById('test').innerHTML = p.getY();
requestAnimationFrame(render);
}
}
window.addEventListener("load", start);
</script>
</head>
<body>
<canvas id="canvas" width="1000" height="300"></canvas>
<h2 id="test"></h2>
</body>
</html>`