LoginSignup
6
7

More than 5 years have passed since last update.

canvasでカラフルな円を生成

Posted at

デモ:http://mo49.tokyo/qiita/20160426/

Circleオブジェクトを定義

Circle.js
var Circle = function(){
  // デフォルトで呼び出されるメソッドを定義
  return this.set();
};

Circle.prototype.set = function(){
  var radian = Math.random() * (Math.PI * 360);
  this.x = cv.width * Math.random(); 
  this.y = cv.height * Math.random(); 
  this.to_x = Math.cos( radian );
  this.to_y = Math.tan( radian );
  this.speed = Math.random() * 3 + 2;
  this.size = Math.random() * 8 + 3;
  // this.color(); // 初回だけならこちらで設定
};

Circle.prototype.move = function(){
  this.x += this.to_x * this.speed;
  this.y += this.to_y * this.speed;
  this.out_square_in();
  this.color();
};

// 画面からはみ出したとき戻す
Circle.prototype.out_square_in = function(){
  if( this.x + this.size < 0 ) this.x = cv.width;
  if( cv.width < this.x ) this.x = 0 - this.size;
  if( this.y + this.size < 0 ) this.y = cv.height;
  if( cv.height < this.y ) this.y = 0 - this.size;
};

Circle.prototype.color = function(){
  this.r = Math.floor(Math.random()*255);
  this.g = Math.floor(Math.random()*255);
  this.b = Math.floor(Math.random()*255);
};

canvasの処理を記述

main.js
var cv = document.getElementById("cv");
var ctx = cv.getContext("2d");

setCanvasSize();
function setCanvasSize() {
  cv.style.width = window.innerWidth + 'px';
  cv.style.height = window.innerHeight + 'px';
  cv.width = window.innerWidth * window.devicePixelRatio;
  cv.height = window.innerHeight * window.devicePixelRatio;
}
$(window).on('resize load', function(){
  setCanvasSize();
});

// スワイプによるスクロールを禁止させる
document.body.addEventListener('touchstart', function(event) {
  event.preventDefault();
});

// canvasが使用可能か判定
if( cv && cv.getContext ) {
  canvasInit();
}

function canvasInit(){

  var instances = [];
  var count = 0;

  for( var i = 1; i <= 100; i++ ){
    instances.push( new Circle() );
  }

  function draw(){
    // 背景
    var p;
    ctx.fillStyle = "#000";
    ctx.fillRect( 0, 0, cv.width, cv.height );

    // 円
    for ( var i = 0; i < instances.length; i++) {
      p = instances[i];
      ctx.fillStyle = 'rgba(' + p.r + ',' + p.g + ',' + p.b + ', 1)';
      ctx.beginPath();
      ctx.arc( p.x, p.y, p.size, 0, Math.PI * 2, false );     
      if (count > 1500) {
        ctx.arc( p.x, p.y, p.size*3, 0, Math.PI * 2, false );     
        if(count > 2000){ count = 0; }
      }
      count++;
      ctx.fill();
      p.move();
    }
  setInterval(draw, 50);

}

 引用
JavaScriptで学ぶ オブジェクト指向入門
ブラウザいっぱいのキャンバスを作る

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7