LoginSignup
0
0

More than 3 years have passed since last update.

年末まで毎日webサイトを作り続ける大学生 〜65日目 文字を泳がせる〜

Last updated at Posted at 2019-12-22

はじめに

こんにちは!@70days_jsです。
今日は文字を泳がせてみました。(gif)↓
test3.gif

65日目。(2019/12/22)
よろしくお願いします。

サイトURL

やったこと

文字を泳がせてみました。
別の言い方をすると、文字がランダムなスピードでY方向の移動をくり返しています。

html↓


 <body>
    <canvas id="canvas"></canvas>
  </body>

canvasを使っています。

css↓

body {
  margin: 0;
}
#canvas {
  background-color: black;
}

bodyのmarginを消して、背景を黒にしています。

JavaScript↓


let canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  twidth = (canvas.width = window.innerWidth),
  theight = (canvas.height = window.innerHeight),
  chars = [],
  fontSize = Math.random() * 100,
  countNumber = 1,
  flag = true;
chars2 = [
  "",
  "",
  "",
......
  "",
  ""
];

function Character(ctx) {
  this.ctx = ctx;
  this.x = Math.floor(Math.random() * twidth);
  this.y = Math.floor(Math.random() * theight);
  this.size = fontSize;
  this.char = chars2[Math.floor(Math.random() * chars2.length)];
  this.v = Math.floor(Math.random() * 5);
}

Character.prototype.render = function() {
  this.draw();
  this.positionChange();
};

Character.prototype.positionChange = function() {
  this.y -= this.v + 1;
  if (this.y < 0) this.y = theight;
  if (this.y > theight) this.y = 0;
};

Character.prototype.draw = function() {
  let ctx = this.ctx;
  ctx.beginPath();
  ctx.fillStyle = "rgba(31, 227, 13, .5)";
  ctx.font = this.size + "px Arial";
  ctx.fill();
  ctx.fillText(this.char, this.x, this.y);
  ctx.closePath();
};

for (var i = 0; i < 100; i++) {
  fontSize = Math.random() * 15;
  let char = new Character(ctx);
  chars.push(char);
}

function render() {
  ctx.clearRect(0, 0, twidth, theight);
  for (var i = 0; chars.length > i; i++) {
    let char = chars[i];
    char.render();
  }
  requestAnimationFrame(render);
}

render();

昨日作ったCharacterコンストラクターを再利用しています。
メソッドは新たにpositionChange()メソッドを加えました。

Y方向の移動をthis.vを使って変更しています。
this.vはランダムで作っているので、あまり遅すぎるものを警戒して最後に+1しています。

感想

とてもシンプルなコードですが、文字が動いているのはワクワクしますね。
ひらがなっていいな。

最後まで読んでいただきありがとうございます。明日も投稿しますのでよろしくお願いします。

0
0
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
0
0