canvaas にランダムな点を撒く
by abbcd
HTML
<canvas id="can"></canvas>
CSS
#can {
background: #efefef;
}
JavaScript
$(document).ready(function () {
var SAMPLE = {};
SAMPLE.Main = (function () {
// 頂点
function Vertex(x, y) {
this.x = x;
this.y = y;
// 描画
this.draw = function(){
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, 360, true);
ctx.fill();
};
}
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));
// ランダムに頂点を追加
for(i = 0; i <= 10; i++)
{
list.push(new Vertex(
Math.floor(Math.random() * canDom.width),
Math.floor(Math.random() * canDom.height)));
}
}
// 頂点リストを描画
function drawVertexList(list)
{
for (i = 0; i < list.length; i++)
{
list[i].draw();
}
}
// 開始
function init() {
// canvas のサイズを指定
canDom.width = 400;
canDom.height = 350;
// 頂点リストを初期化
initializeVertexList(vertexList);
// 頂点リストを描画
drawVertexList(vertexList);
}
// 開始
init();
})();
});