はじめに
こんにちは!@70days_jsです。
昨日に引き続き円で遊びました。
昨日は自動でしたが、今日はマウスに合わせて円が作られます。(gif)↓
今日は69日目。(2019/12/26)
よろしくお願いします。
サイトURL
やったこと
マウスに合わせて円を作ります。
cssなし。
html↓
<body>
<canvas id="canvas"></canvas>
</body>
JavaScript↓
let canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
canvasW = (canvas.width = window.innerWidth),
canvasH = (canvas.height = window.innerHeight),
circles = [];
function Circle(ctx, x, y, size) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.size = size;
this.r = Math.random() * 256;
this.g = Math.random() * 256;
this.b = Math.random() * 256;
this.a = Math.random() * 11;
this.v = Math.ceil(Math.random() * 3);
}
Circle.prototype.render = function() {
this.draw();
this.statusChange();
};
Circle.prototype.draw = function() {
let color = this.r + "," + this.g + "," + this.b + "," + this.a;
let ctx = this.ctx;
let random = Math.ceil(Math.random() * 2);
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
if (random > 1) {
ctx.strokeStyle = "rgba(" + color + ")";
ctx.stroke();
} else {
ctx.fillStyle = "rgba(" + color + ")";
ctx.fill();
}
ctx.closePath();
};
Circle.prototype.statusChange = function() {
this.size += 1;
if (this.size > canvasW / 3 || this.size > canvasH / 3) {
this.size = 0;
}
};
document.body.addEventListener("mousemove", createCircleObject);
function createCircleObject(e) {
let x = e.pageX;
let y = e.pageY;
let size = Math.random() * 10;
let circle = new Circle(ctx, x, y, size);
circles.push(circle);
}
function render() {
ctx.clearRect(0, 0, canvasW, canvasH);
circles.forEach(function(obj) {
obj.render();
});
requestAnimationFrame(render);
}
render();
大部分は昨日と同じなので、違うところを解説していきます。
まずオブジェクトの作成はイベントリスナーでマウスの移動で取っています。
document.body.addEventListener("mousemove", createCircleObject);
オブジェクトはマウスの通った位置にできます。
function createCircleObject(e) {
let x = e.pageX;
let y = e.pageY;
let size = Math.random() * 10;
let circle = new Circle(ctx, x, y, size);
circles.push(circle);
}
昨日はsizeがもっと大きかったのですが、今回は小さめに微調整しました。
円はだんだん大きくなっていくのですが、昨日より最大の大きさを低めに設定しました。
また、最大限大きくなっても位置は変わらず、サイズのみ0から始めることで、z軸の移動もしているような視差効果が得られます。
if (this.size > canvasW / 3 || this.size > canvasH / 3) {
this.size = 0;
gifを見ているとなんとなく奥から手前に移動しているように見えませんでしょうか?
感想
オセロ作らねば。
最後まで読んでいただきありがとうございます。明日も投稿しますのでよろしくお願いします。