p5.js入門記 -その1雪を降らせる-
10941 ワード
はじめに
p5.jsの入門を終わらせた後、実際に作品を作っていこうという記事です。
探り探りですが書いていこうと思います。
入門時に参考にしたもの一覧
-
ドットインストール p5.js入門
-
paizaラーニング JavaScript入門編
- p5.js公式サイト
- p5.js で様々なパターンを描画してみた
雪を降らせる
冬なので雪を降らせてみたいと思いました。
【参考】
- 公式サイトのサンプル: Snowflakes
- 公式サイトのサンプル: Load and Display Image
【使用素材】
by いらすとや
成果物
コード
雪部分はほぼサンプルコード通りですが、粒の大きさなど適宜調整しました。
sample.js
let snowflakes = []; // array to hold snowflake objects
var bg;
var img;
function setup() {
createCanvas(720, 400);
fill(240);
noStroke();
bg = loadImage("bg_snow_jutaku.jpg");
img = loadImage("kids_hashirimawaru_snow.png");
}
function draw() {
image(bg,0,0);
image(img, width/3, 80, img.width/2, img.height/2);
let t = frameCount / 60; // update time
// create a random number of snowflakes each frame
for (var i = 0; i < random(10); i++) {
snowflakes.push(new snowflake()); // append snowflake object
}
// loop through snowflakes with a for..of loop
for (let flake of snowflakes) {
flake.update(t); // update snowflake position
flake.display(); // draw snowflake
}
}
// snowflake class
function snowflake() {
// initialize coordinates
this.posX = 0;
this.posY = random(-50, 0);
this.initialangle = random(0, 2 * PI);
this.size = random(6, 12);
// radius of snowflake spiral
// chosen so the snowflakes are uniformly spread out in area
this.radius = sqrt(random(pow(width / 2, 2)));
this.update = function(time) {
// x position follows a circle
let w = 0.6; // angular speed
let angle = w * time + this.initialangle;
this.posX = width / 2 + this.radius * sin(angle);
// different size snowflakes fall at slightly different y speeds
this.posY += pow(this.size, 0.5);
// delete snowflake if past end of screen
if (this.posY > height) {
let index = snowflakes.indexOf(this);
snowflakes.splice(index, 1);
}
};
this.display = function() {
ellipse(this.posX, this.posY, this.size);
};
}
おわりに
また次回、よろしくお願いします!
Author And Source
この問題について(p5.js入門記 -その1雪を降らせる-), 我々は、より多くの情報をここで見つけました https://qiita.com/choco_py3/items/02200022d9b6e73544f8著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .