Chrome拡張(6)p5.jsで作る,バックグラウンドで動作するChrome拡張
タイトル通り,背景でなんとなくジェネラティブに動くものをChrome拡張を使ってやりたいと思い立った.今回は,個人的な興味でp5.jsを使うことにした.その理由は以下.
- p5.js自体が微妙に重い(通常版が2.6MB,min版が1.2MB)ので,逆にローカルにダウンロードする拡張では機能する良い使い方かもしれないという考え
- JavaScriptでキャンバスみたいなことが全くわからないのでProcessingライクに書けるp5.jsが使えないかという目論見
結論として,四苦八苦して,なんとなくイメージしているようなフレームの所までたどり着けた.this忘れやクラスっぽい書き方などでたくさんのエラーを吐くなか,console.logで確認したりしながら書いた.素のJavaScript苦手.
manifest.jsonの中で書いているp5.jsのライブラリはウェブサイトでダウンロードしてください.念のため一式アップします.script.jsは基本的にp5.jsでサラで書くのが良さげ.
コード
- manifest.json
{ "name" : "Google Extension using p5.js", "version" : "0.1", "manifest_version" : 2, "description" : "chrome extension using p5.js / background animation", "content_scripts" : [{ "matches" : ["<all_urls>"], "js" : ["js/jquery.min.js","js/p5.min.js","js/p5.dom.js","js/p5.sound.js","js/script.js"] }] }
- script.js
var w; var h; var balls = []; var num = 300; function setup(){ // ページ全体のサイズをjQueryで取得 w = $(document).width() h = $(document).height(); // ページ全体のサイズにsizeを指定 var canvas = createCanvas(w,h); colorMode(HSB,360,100,100,100); // p5.jsのキャンバスのCSS指定 canvas.position(0,0); canvas.style('z-index','-1'); console.log("p5:setup"); for(var i = 0; i < num; i++){ var x = random(w); var y = random(h); balls.push(new Ball(x,y)); } } function draw(){ background(0,0,100); for(var i = 0; i < num; i++){ balls[i].update(); balls[i].draw(); } } function windowResized() { w = $(document).width() h = $(document).height(); resizeCanvas(w, h); } function Ball(_x,_y){ this.x = _x; this.y = _y; this.theta =random(TWO_PI); this.dx = cos(this.theta) * 5; this.dy = sin(this.theta) * 5; this.c = color(random(360),80,100); this.d = random(25,50); this.update = function(){ this.x += this.dx; this.y += this.dy; if(this.x - this.d/2 < 0 || this.x + this.d/2 > w){ this.dx *= -1; } if(this.y - this.d/2 < 0 || this.y + this.d/2 > h){ this.dy *= -1; } } this.draw = function(){ fill(this.c); noStroke(); // console.log(this.x,this.y); ellipse(this.x,this.y,this.d,this.d); } }