ボールのオブジェクトタイプは、新しいコンストラクタ関数ball(color)で作成されます。 プロパティには、キャンバスにペイントしてランダムな方向に移動させる必要があるすべてのプロパティが含まれます。 orangeBall =新しいボール( 'オレンジ')が1つ作成されると、キャンバス上での動きを含めてうまく表示されます。しかし、もう1つ追加すると、両方が点滅し始めます。 解決方法おかげさまで キャンバスにボールのブレイキングを固定する方法は?
<!DOCTYPE html>
<html lang="he">
<head>
<meta charset="utf-8" />
<title>
כדורים קופצים רנדומלית בצבעים שונים
</title>
<style>
html,body {
margin: 0;
padding: 0;
background: black;
}
.container { width:900px; margin:0 auto; }
#canvas { background:#8613eb; border:1px solid #cbcbcb; }
</style>
<script>
var ctx;
var H = 800;
var W = 800;
window.onload = function() {
ctx = canvas.getContext("2d");
canvas.width=W;
canvas.height=H;
function ball(color) {
//life - the amount of time to show the ball in the screen
this.life = 60*1000, //1 minute
this.color = arguments.length==1 ? color: 'white';
this.x= Math.round(Math.random()*W);
this.y= Math.round(Math.random()*H);
this.radius= 10 + Math.round(Math.random()*50);// between 10-60
this.dx=1+ Math.round(Math.random()*5); //between 1-6
this.dy= 2+ Math.round(Math.random()*4); //between 2-6
this.startAngel= 0;
this.endAngel= 2*Math.PI; //360deg
this.speed= 3+Math.round(Math.random()*50) //3-50msec
this.show = function() {
//first clear the previous ball
ctx.clearRect(0,0,canvas.width,canvas.height);
var xClear = (this.x-this.radius) <=0 ? 0:(this.x - this.radius);
var yClear = (this.y-2*this.radius) <=0 ? 0:(this.y - 2*this.radius);
ctx.clearRect(xClear,yClear,canvas.width,canvas.height);
//lets stroke the ball
ctx.beginPath();
ctx.fillStyle = this.color;
this.x+=this.dx;
this.y+=this.dy;
if (this.x<0 || this.x>W) {
this.dx=-this.dx;
}
if (this.y<0 || this.y>H) {
this.dy=-this.dy;
}
ctx.arc(this.x,this.y,this.radius,this.startAngel,this.endAngel);
ctx.closePath();
ctx.fill();
this.life-=this.speed;
var _this = this;
// creating new property in the ball 'timePointer'
this.timePointer = this.life<=0 ?
clearInterval(this.timePointer):
setTimeout(function() {
_this.show();
},this.speed);
}
this.show();
};
orangeBall = new ball('orange');
blackBall = new ball('black');
// whiteBall = new ball('white');
// yellowgeBall = new ball('yellow');
// pinkBall = new ball('pink');
// blueBall = new ball('blue');
// greenBall = new ball('green');
};
</script>
</head>
<body>
<div class="container">
<canvas id="canvas">Your browser doesn't support this game.</canvas>
</div>
</body>
</html>
*プロトタイプ*と*相続*を見てみましょう。 youveが多くのボールを持っている場合、あなたのコードはブラウザを遅くします... –