プログラミングの初心者の方が楽しくプログラミングを学べるように、ゲームみたいにキャラクターにしゃべらせる形でプログラムの説明を行ってみました。
このボタンをクリックすると開始します。(約 分)
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<script src="a.js"></script>
<script>
function onloadx() {
app = new App( "test_canvas" );
app.start();
}
</script>
</head>
<body onload="onloadx()">
<canvas id="test_canvas" width="512" height="448" style="
border : solid 1px black;
">
There is no canvas.
</canvas>
</body>
</html>
class App {
constructor( canvasId ) {
this.cc = document.getElementById( canvasId ).getContext( "2d", { alpha: false } );
this.cc.tmp = {
width : this.cc.canvas.width,
height : this.cc.canvas.height,
}
this.balls = new Array();
for( let color of [ "rgb(255,0,0)",
"rgb(0,255,0)",
"rgb(0,0,255)",
"rgb(255,0,255)",
"rgb(0,255,255)",
"rgb(255,255,0)",
] ) {
let ball = new Ball( color, this.cc );
ball.addX = 5 + Math.random() * 10;
ball.addY = 5 + Math.random() * 10;
ball.x = Math.random() * this.cc.tmp.width;
ball.y = Math.random() * this.cc.tmp.height;
this.balls.push( ball );
}
}
start() {
if( typeof this.timerId === "undefined" )
this.timerId = setInterval( this.frame.bind( this ), 100 );
}
stop() {
if( typeof this.timerId !== "undefined" ) {
clearInterval( this.timerId );
delete this.timerId;
}
}
frame() {
for( let ball of this.balls ) {
ball.frame();
}
this.draw( this.cc );
}
draw( cc ) {
cc.fillStyle = "white";
cc.fillRect( 0, 0, cc.tmp.width, cc.tmp.height );
for( let ball of this.balls ) {
ball.draw( cc );
}
}
}
class Ball {
constructor( color, cc ) {
this.color = color;
this.cc = cc;
this.x = 0;
this.y = 0;
this.addX = 1;
this.addY = 1;
}
frame() {
this.x += this.addX * 1.25;
this.y += this.addY * 1.25;
//check.
if( this.x > this.cc.tmp.width ) {
this.addX *= -1;
}
if( this.x < 0 ) {
this.addX *= -1;
}
if( this.y > this.cc.tmp.height ) {
this.addY *= -1;
}
if( this.y < 0 ) {
this.addY *= -1;
}
}
draw( cc ) {
cc.beginPath();
cc.arc( this.x, this.y, 75, 0, 6.28, false );
cc.closePath();
cc.globalAlpha = 0.5;
cc.fillStyle = this.color;
cc.fill();
// cc.globalAlpha = 1; //この行コメントアウトで残像
}
}