我使用laravel 5.5,vuejs和vue-router创建了一个spa / rest / crud应用程序。现在我想到了这样一个想法:使用一个组件来登陆页面,并用画布调整一点。 (原来是p5.js,但我现在放弃了。)到目前为止一切顺利。我让Vue组件通过Vue-Router工作,对于前页我创建了一个带有自定义指令的组件,该指令将模板中的canvas元素提供给它的数据(以球对象的形式)
现在因为我不得不切换到我不熟悉的Canvas,我遇到了问题。作为测试,我将4个球放入阵列中。但只有1人出现。现在当我禁用clearRect功能时。他们确实以凌乱的方式出现。我不得不使用beginPath()显然是为了防止球落后于#39;。但是,当我这样做时,只有一个出现。也许这是一件我能忽视的简单事情。我发布了我认为导致问题的部分:
<script>
export default {
data: function(){
return {
}
},
directives: {
bindCanvas: {
inserted: function (el) {
var ctx = el.getContext("2d");
var Ball = function(x,y,r){
this.position = {};
this.position.x = x;
this.position.y = y;
//i could not use vectors so i came up with this solution
this.velocity = {x:0,y:0};
this.acceleration = {x:0,y:0};
this.radius = r;
};
Ball.prototype.addForce = function(x,y){
this.acceleration.x += x/1000;
this.acceleration.y += y/1000;
};
Ball.prototype.move = function(){
this.position.x += this.velocity.x;
this.position.y += this.velocity.y;
this.velocity.x += this.acceleration.x;
this.velocity.y += this.acceleration.y;
//reset acceleration to 0
this.acceleration.x *= 0;
this.acceleration.y *= 0;
};
Ball.prototype.display = function(){
//here is the problem somewhere i think.
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.beginPath();
ctx.fillStyle = 'rgb(255,0,0)';
ctx.arc(this.position.x,this.position.y,this.radius,0, Math.PI*2);
ctx.fill();
};
Ball.prototype.checkBorders = function(){
if(this.position.x > ctx.canvas.width-(this.radius/2)){
this.velocity.x = this.velocity.x *-1;
} else if (this.position.x < 0){
this.velocity.x *= -1;
}
if (this.position.y > ctx.canvas.height-(this.radius/2)){
this.velocity.y *= -1;
} else if(this.position.y < 0){
this.velocity.y *= -1;
}
};
Ball.prototype.checkMaxSpeed = function(){
if(this.velocity.x > 0.5){
this.velocity.x = 0.5;
}
if(this.velocity.x < -0.5){
this.velocity.x = -0.5;
}
if(this.velocity.y > 0.5){
this.velocity.y = 0.5;
}
if(this.velocity.y < -0.5){
this.velocity.y = -0.5;
}
};
var arrayOfBalls = [];
for(var i=0;i<=3;i++){
arrayOfBalls.push(new Ball(Math.random()*100,Math.random()*100,Math.random()*100));
}
var animate = function(){
for(var j = arrayOfBalls.length-1; j>= 0; j--){
arrayOfBalls[j].checkBorders();
arrayOfBalls[j].checkMaxSpeed();
arrayOfBalls[j].addForce(Math.random(),Math.random());
arrayOfBalls[j].addForce(0,0.00098);
arrayOfBalls[j].display();
arrayOfBalls[j].move();
}
window.requestAnimationFrame(animate);
};
animate();
}
}
},
}
答案 0 :(得分:0)
正如我在评论中所提到的,问题是每个球的display()函数中的clearRect()调用。通常情况下,只需在动画的每个帧/循环中清除画布,因此clearRect可以放在动画函数的顶部,如此处所示......
var animate = function(){
// Clear the canvas just once each animation frame here
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
for(var j = arrayOfBalls.length-1; j>= 0; j--) {
arrayOfBalls[j].checkBorders();
arrayOfBalls[j].checkMaxSpeed();
arrayOfBalls[j].addForce(Math.random(),Math.random());
arrayOfBalls[j].addForce(0,0.00098);
arrayOfBalls[j].display();
arrayOfBalls[j].move();
}
window.requestAnimationFrame(animate);
};