create.js - node

by uto usui

HTML

<div class="wrap">

  <h1>create.js</h1>
  <p>node motion</p>
  <canvas id="myCanvas" width="600" height="600"></canvas>

</div>

SCSS

body {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  font-family: Helvetica, 'Helvetica';
  text-align: center;
}

h1 {
  font-size: 42px;
  font-weight: bold;
  color: #32355a;
}

canvas {
	width: 300px;
	height: 300px;
  margin: 20px auto;
  border: 3px dashed rgba(#32355a, .55);
}

JavaScript

window.addEventListener("load", init);

var stage;
var stageWidth;
var stageHeight;
var balls = [];
var ballCount = 30;
var ratio = 1 / 2000;
var max = 100;
var limit = max * max;
var colorInt = Math.floor(Math.random() * 0xFFFFFF) * 1000;
var background = new createjs.Shape();
//
function init() {
  var color = createjs.Graphics.getRGB(colorInt);
  var canvasElement = document.getElementById("myCanvas");
  stage = new createjs.Stage(canvasElement);
  stageWidth = canvasElement.width;
  stageHeight = canvasElement.height;
  stage.addChild(background);
  for (var i = 0; i < ballCount; i++) {
    var nX = Math.random() * stageWidth;
    var nY = Math.random() * stageHeight;
    var velocityX = (Math.random() - 0.5) * 5;
    var velocityY = (Math.random() - 0.5) * 5;
    var ball = createBall(2, color, nX, nY, velocityX, velocityY);
    balls.push(ball);
    stage.addChild(ball);
  }
  createjs.Ticker.addEventListener("tick", move);
}
function createBall(radius, color, nX, nY, velocityX, velocityY) {
  var ball = new createjs.Shape();
  drawBall(ball.graphics, radius, color);
  ball.x = nX;
  ball.y = nY;
  ball.velocityX = velocityX;
  ball.velocityY = velocityY;
  return ball;
}
function drawBall(myGraphics, radius, color) {
  myGraphics.beginFill(color);
  myGraphics.drawCircle(0, 0, radius);
}
function move(eventObject) {
  for (var i = 0; i < ballCount; i++) {
    var ball = balls[i];
    var nX = ball.x;
    var nY = ball.y;
    nX += ball.velocityX;
    nY += ball.velocityY;
    ball.x = roll(nX, stageWidth);
    ball.y = roll(nY, stageHeight);
  }
  background.graphics.clear();
  for (i = 0; i < ballCount - 1; i++) {
    var ball0 = balls[i];
    for (var j = i + 1; j < ballCount; j++) {
      var ball1 = balls[j];
      spring(ball0, ball1);
    }
  }
  stage.update();
}
function roll(value, length) {
  if (value > length) {
    value -= length;
  } else if (value < 0) {
    value += length;
  }
  return value;
}
function spring(object0, object1) {
  var...