一.簡介
Processing.js作者是John Resig,這是繼Jquery之後,他的第二個力作。
Processing.js提供了教學可視化的程式設計語言及運行環境。通過編寫processing程式,教師可以將複雜的物理、化學、數學原理形象的展示給學生。比如繪製各種曲線圖,波線,粒子,繪製分子結構,當然在生理衛生課上還可以繪製一群小蝌蚪在遊泳等動態圖形。
Processing.js是一個開放的程式設計語言,在不使用Flash或Java小程式的前提下, 可以實現程式映像、動畫和互動的應用。
Processing.js使用JavaScript繪製形狀sharp和操作HTML5 canvas元素產生映像動畫。
Processing.js是輕量,易於瞭解掌握,並提出一個理想的工具,可視化的資料,建立使用者介面和開發基於Web的遊戲。
二.核心函數
view sourceprint?01 // Global variables 全域變數
02 int radius = 50.0;
03 int X, Y;
04 int nX, nY;
05 int delay = 16;
06
07 // Setup the Processing Canvas初始化設定
08 void setup(){
09 size( 200, 200 );
10 strokeWeight( 10 );
11 frameRate( 15 );
12 X = width / 2;
13 Y = width / 2;
14 nX = X;
15 nY = Y;
16 }
17
18 // Main draw loop 主要繪畫函數功能
19 void draw(){
20
21 radius = radius + sin( frameCount / 4 );
22
23 // Track circle to new destination
24 X+=(nX-X)/delay;
25 Y+=(nY-Y)/delay;
26
27 // Fill canvas grey
28 background( 100 );
29
30 // Set fill-color to blue
31 fill( 0, 121, 184 );
32
33 // Set stroke-color white
34 stroke(255);
35
36 // Draw circle
37 ellipse( X, Y, radius, radius );
38 }
39
40
41 // Set circle's next destination 當使用者滑鼠在Canvas移動時產生的action
42 void mouseMoved(){
43 nX = mouseX;
44 nY = mouseY;
45 }
三.世界最短的時鐘代碼誕生
view sourceprint?1 void draw() {
2 size(200, 200);background(0); fill(80); noStroke(); ellipse(100, 100, 160, 160); stroke(255);
3 line(100, 100, cos( TWO_PI*second()/60- HALF_PI) * 70 + 100, sin(TWO_PI*second()/60- HALF_PI) * 70 + 100);
4 line(100, 100, cos( TWO_PI*minute()/60- HALF_PI) * 60 + 100, sin(TWO_PI*minute()/60- HALF_PI) * 60 + 100);
5 line(100, 100, cos(TWO_PI*(hour()%12)/12- HALF_PI) * 50 + 100, sin(TWO_PI*(hour()%12)/12- HALF_PI) * 50 + 100);
6 }
可以看得出,代碼語意化非常強,一個圓,三條線,這也是這個架構所要達到的目的之一。
四.完整代碼
view sourceprint?01 <!DOCTYPE html>
02 <html>
03 <head>
04 <body>
05 <script src="http://files.cnblogs.com/iamzhanglei/processing.js" type="text/javascript"></script>
06 <script type="application/processing">
07 void draw() {
08 size(200, 200);background(0); fill(80); noStroke(); ellipse(100, 100, 160, 160); stroke(255);
09 line(100, 100, cos( TWO_PI*second()/60- HALF_PI) * 70 + 100, sin(TWO_PI*second()/60- HALF_PI) * 70 + 100);
10 line(100, 100, cos( TWO_PI*minute()/60- HALF_PI) * 60 + 100, sin(TWO_PI*minute()/60- HALF_PI) * 60 + 100);
11 line(100, 100, cos(TWO_PI*(hour()%12)/12- HALF_PI) * 50 + 100, sin(TWO_PI*(hour()%12)/12- HALF_PI) * 50 + 100);
12 }
13 </script>
14 <canvas>你的瀏覽器不支援HTML5,請使用Google、IE9或者Firefox瀏覽器··</canvas>
15 </body>
16 </html>