processing.js 學習(二)

使用processing有兩種方式,我們將逐一介紹。

第一種(推薦)

文件構成:

  • processing.js
  • anything.html
  • anything.pde

    即上篇所示。
    其中,anything.html中要有

<script src="processing.js"></script> 
<canvas data-processing-sources="anything.pde"></canvas>

anything.pde中要有

void setup()
{
  size(200,200);
  background(125);
  fill(255);
  noLoop();
  PFont fontA = loadFont("courier");
  textFont(fontA, 14);  
}

void draw(){  
  text("Hello Web!",20,20);
  println("Hello ErrorLog!");
}

也就是說,實現processing的代碼全部寫在了草圖上。

第二種

文件構成:

  • processing.js
  • anything.html

其中,anything.html是醬紫的

<script src="processing.js"></script>
<script type="text/processing" data-processing-target="mycanvas">
void setup()
{
  size(200,200);
  background(125);
  fill(255);
  noLoop();
  PFont fontA = loadFont("courier");
  textFont(fontA, 14);  
}

void draw(){  
  text("Hello Web!",20,20);
  println("Hello ErrorLog!");
}
</script>
<canvas id="mycanvas"></canvas>

注意到了嗎?這種情況下canvas不需要 data-processing-sources屬性。


用JavaScript寫processing代碼

示例是一個時鐘。
這裏寫圖片描述

<html>
<head>
  <script src="processing.js"></script>
</head>
<body><h1>Processing.js</h1>
<h2>Simple processing.js via JavaScript</h2>
<p>Clock</p>

<p><canvas id="canvas1" width="200" height="200"></canvas></p>

<script id="script1" type="text/javascript">

// 通過一個函數便捷的把js代碼加到canvas上

function sketchProc(processing) {
  // 重載繪製函數,默認每秒60次
  processing.draw = function() {
    // 設置中心點和長指針的長度
    var centerX = processing.width / 2, centerY = processing.height / 2;
    var maxArmLength = Math.min(centerX, centerY);

    function drawArm(position, lengthScale, weight) {      
      processing.strokeWeight(weight);
      processing.line(centerX, centerY, 
        centerX + Math.sin(position * 2 * Math.PI) * lengthScale * maxArmLength,
        centerY - Math.cos(position * 2 * Math.PI) * lengthScale * maxArmLength);
    }

    // 擦除背景
    processing.background(224);

    var now = new Date();

    // 移動時針
    var hoursPosition = (now.getHours() % 12 + now.getMinutes() / 60) / 12;
    drawArm(hoursPosition, 0.5, 5);

    // 移動分針
    var minutesPosition = (now.getMinutes() + now.getSeconds() / 60) / 60;
    drawArm(minutesPosition, 0.80, 3);

    // 移動秒針
    var secondsPosition = now.getSeconds() / 60;
    drawArm(secondsPosition, 0.90, 1);
  };

}

var canvas = document.getElementById("canvas1");
//把函數加到canvas上 
var p = new Processing(canvas, sketchProc);
// p.exit(); 用於分離
</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章