<!DOCTYPE html>
<html>
<head>
<title>音を鳴らす正方形</title>
</head>
<body onload="init();">
<canvas id="canvas" width="400" height="400"></canvas>
<script>
/* キャンバスの初期化 */
function init() {
/* キャンバスの取得 */
var canvas = document.getElementById('canvas');
/* コンテキストの取得 */
var ctx = canvas.getContext('2d');
/* 正方形の初期位置と速度 */
var x = canvas.width / 2;
var y = canvas.height / 2;
var dx = 2;
var dy = -2;
/* 音を鳴らすためのオーディオコンテキスト */
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
/* サウンドの初期化 */
var oscillator = audioCtx.createOscillator();
oscillator.connect(audioCtx.destination);
oscillator.start();
/* アニメーションの実行 */
function draw() {
/* 背景の塗りつぶし */
ctx.clearRect(0, 0, canvas.width, canvas.height);
/* 正方形の描画 */
ctx.beginPath();
ctx.rect(x, y, 50, 50);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
/* 正方形の反射 */
if(x + dx > canvas.width - 50 || x + dx < 0) {
dx = -dx;
/* 音の高さをランダムに変化させる */
oscillator.frequency.value = Math.random() * 1000 + 200;
}
if(y + dy > canvas.height - 50 || y + dy < 0) {
dy = -dy;
/* 音の高さをランダムに変化させる */
oscillator.frequency.value = Math.random() * 1000 + 200;
}
/* 正方形の移動 */
x += dx;
y += dy;
/* アニメーションの継続 */
requestAnimationFrame(draw);
}
/* アニメーションの開始 */
draw();
}
</script>
</body>
</html>
※ ジョークとして、正方形が画面外に消えても音だけは聞こえるようにした点です。