直線の描画を利用した三角形の集合体描画(アニメーション風)
前回作成した三角形の集合体をアニメーションっぽく描画してみたHTML
JavaScript
$(document).ready(function () {
// キャンバスの準備
// 記事ごとに個別の ID を設定する
var can = document.getElementById('canvas3');
if (can.getContext) {
// 2次元の描画コンテクストを取得
var ctx = can.getContext('2d');
var startLeft = 50;
var StartTop = 350;
var EndTop = 400;
var timer; //タイマ
var delay = 50; //タイマを実行する間隔
// 座標位置を移動するための加算値
var addValue = 0;
var clearLoop = function () {
// canvasクリア
ctx.clearRect(0, 0, can.width, can.height);
}
var drawLoop = function () {
// 大きい正三角形を描画する
for (downCount = 0; downCount <= 5; downCount++) {
var correctionLeft = 25 * downCount + addValue;
var correctionTop = 50 * downCount + addValue;
// 白抜き三角形描画
for (idx = 1; idx <= 6 - downCount; idx++) {
ctx.beginPath();
ctx.moveTo(startLeft * idx + correctionLeft, EndTop - correctionTop);
ctx.lineTo(startLeft * (0.5 + idx) + correctionLeft, StartTop - correctionTop);
ctx.lineTo(startLeft * (1 + idx) + correctionLeft, EndTop - correctionTop);
ctx.closePath();
ctx.strokeStyle = "#000080";
ctx.stroke();
}
// 黒塗り三角形描画
for (idx = 1; idx <= 5 - downCount; idx++) {
ctx.beginPath();
ctx.moveTo(startLeft * (0.5 + idx) + correctionLeft, StartTop - correctionTop);
ctx.lineTo(startLeft * (1.5 + idx) + correctionLeft, StartTop - correctionTop);
ctx.lineTo(startLeft * (1 + idx) + correctionLeft, EndTop - correctionTop);
ctx.closePath();
ctx.fillStyle = "#000080";
ctx.fill();
}
}
}
var drawLoop2 = function () {
// 大きい正三角形を描画する
for (downCount = 0; downCount <= 5; downCount++) {
// 座標の補正
var correctionLeft = 25 * downCount + addValue;
var correctionTop = 50 * downCount - addValue;
// 白抜き三角形描画
for (idx = 1; idx <= 6 - downCount; idx++) {
ctx.beginPath();
ctx.moveTo(startLeft * idx + correctionLeft, EndTop - correctionTop);
ctx.lineTo(startLeft * (0.5 + idx) + correctionLeft, StartTop - correctionTop);
ctx.lineTo(startLeft * (1 + idx) + correctionLeft, EndTop - correctionTop);
ctx.closePath();
ctx.strokeStyle = "#000080";
ctx.stroke();
}
// 黒塗り三角形描画
for (idx = 1; idx <= 5 - downCount; idx++) {
ctx.beginPath();
ctx.moveTo(startLeft * (0.5 + idx) + correctionLeft, StartTop - correctionTop);
ctx.lineTo(startLeft * (1.5 + idx) + correctionLeft, StartTop - correctionTop);
ctx.lineTo(startLeft * (1 + idx) + correctionLeft, EndTop - correctionTop);
ctx.closePath();
ctx.fillStyle = "#000080";
ctx.fill();
}
}
}
// 繰り返し関数
var loop = function () {
// 座標位置の加算
addValue = addValue + 1;
// canvasクリア
clearLoop();
// 大きい正三角形を描画する
drawLoop();
// 大きい正三角形を描画する
drawLoop2();
if (addValue < 100) {
// タイマリセット
clearTimeout(timer);
timer = setTimeout(loop, delay);
}
}
// 繰り返し関数呼び出し
loop();
}
});