canvas に撒いた点を移動させる
by abbcd
HTML
<canvas id="can"></canvas>
CSS
#can {
background: #efefef;
}
JavaScript
$(document).ready(function () {
var SAMPLE = {};
SAMPLE.Main = (function () {
// 頂点
function Vertex(x, y, vx, vy) {
this.x = x;
this.y = y;
// 固定頂点かどうか(true:固定、false:移動)
this.isStatic = ((vx == undefined || vy == undefined) ? true : false);
// X 軸の移動速度
this.velocityX = ((vx == undefined) ? Math.random() * 0.7 - 0.35 : vx);
// Y 軸の移動速度
this.velocityY = ((vy == undefined) ? Math.random() * 0.7 - 0.35 : vy);
// 頂点を描画
this.draw = function () {
// 固定は黒、移動は赤
ctx.fillStyle = (this.isStatic ? "rgb(66, 66, 66)" : "rgb(255, 66, 22)");
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, 360, true);
ctx.fill();
};
// 頂点を更新
this.update = function () {
// 移動する頂点の場合
if (!this.isStatic) {
// canvas の端で跳ね返す(X)
if (0 > this.x || canDom.width < this.x) {
this.velocityX *= -1;
}
// canvas の端で跳ね返す(Y)
if (0 > this.y || canDom.height < this.y) {
this.velocityY *= -1;
}
// 座標を更新
this.x += this.velocityX;
this.y += this.velocityY;
}
};
}
var canJqObj = $("#can"),
canDom = document.getElementById('can'),
ctx = document.getElementById('can').getContext("2d"),
vertexList = [];
// 頂点リストを初期化
function initializeVertexList(list) {
// 四隅に頂点を追加
list.push(new Vertex(0, 0));
list.push(new Vertex(canDom.width, 0));
list.push(new Vertex(0, canDom.height));
list.push(new Vertex(canDom.width, canDom.height));
//...