使用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>