canvas-tetrisのソースを眺めながら、5x5の格子の色をランダムに変えてみた。sでスタートとストップを交互に繰り返す
整数の乱数値を取りたい時にはrandomしてfloorする
Math.floor(Math.random() * 255)
ループさせたい場合にはsetIntervalで止めたい時にはclearInterval。この例ではrunning = !runningでトグルさせてる。
if( running ){
clearInterval( drawLoop )
var r = Math.floor(Math.random() * 255);
alert("stopped ");
}else{
drawLoop = setInterval(drawMap, 50);
}
running = !running;
以下、全コード
<!DOCTYPE html>
<html>
<head>
<title>Canvas Test</head>
</head>
<body>
<h1 style='text-align:center'>Canvas Test</h1>
<div style='text-align:center'>
<canvas id='game' style='border:solid 2px #aaa;'>
Your browser does not support the <canvas> element.<br>
Please use a normal browser. Hint: Safari, Chrome, Firefox.
</canvas>
</div>
<script type="text/javascript" charset="utf-8">
var SQ = 25; // square side in pixels
var HCOUNT = 5; // horizontal width in squares
var VCOUNT = 5; // vertical width in squares
var WIDTH = SQ * HCOUNT;
var HEIGHT = SQ * VCOUNT;
var BGCOLOR = '#fff';
var canvas = document.getElementById('game');
canvas.width = WIDTH;
canvas.height = HEIGHT;
var ctx = canvas.getContext('2d');
function line( fromx, fromy, tox, toy ){
ctx.beginPath();
ctx.moveTo( fromx, fromy );
ctx.lineTo( tox, toy );
ctx.stroke();
}
ctx.strokeStyle = '#999';
ctx.lineWidth = .5;
function drawMap() {
// clear map and draw grid
ctx.clearRect( 0, 0, WIDTH, HEIGHT );
var currentSquare, w, h, i;
// this loop draws the current map state
for( w = 0; w < HCOUNT; w++ ){
ctx.save();
ctx.translate( w * SQ, 0 ); // Move the canvas horizontally
for( h = 0; h < VCOUNT; h++ ){
ctx.save();
ctx.translate( 0, h * SQ ); // Move the canvas vertically
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
ctx.fillStyle = "rgb("+r+","+g+","+b+")";
ctx.fillRect( 0, 0, SQ, SQ );
ctx.restore();
}
ctx.restore();
}
for( i = 1; i < WIDTH; i++ )
line( i*SQ, 0, i*SQ, HEIGHT );
for( i = 1; i < HEIGHT; i++ )
line( 0, i*SQ, WIDTH, i*SQ );
}
var running = false, drawLoop;
document.onkeydown = function(e) {
var key = e.which;
if( key === 83 ) { // s - stop (pause)
if( running ){
clearInterval( drawLoop )
var r = Math.floor(Math.random() * 255);
alert("stopped ");
}
else{
drawLoop = setInterval(drawMap, 50);
}
running = !running;
}
}
</script>
</body>
</html>