Processing.js reference 涵盖了这一点。
您可以简单地将代码放入.pde 文件(处理IDE 使用的文件类型)。 Processing.js 会为你编译成 JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Hello Web - Processing.js Test</title>
<script src="processing-1.3.6.min.js"></script>
</head>
<body>
<h1>Processing.js Test</h1>
<p>This is my first Processing.js web-based sketch:</p>
<canvas data-processing-sources="hello-web.pde"></canvas>
</body>
</html>
或者您可以直接编写 JavaScript,然后将其包含在单独的 .js 文件中:
在单独的文件中:
function sketchProc(processing) {
// Override draw function, by default it will be called 60 times per second
processing.draw = function() {
// determine center and max clock arm length
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);
}
// erase background
processing.background(224);
var now = new Date();
// Moving hours arm by small increments
var hoursPosition = (now.getHours() % 12 + now.getMinutes() / 60) / 12;
drawArm(hoursPosition, 0.5, 5);
// Moving minutes arm by small increments
var minutesPosition = (now.getMinutes() + now.getSeconds() / 60) / 60;
drawArm(minutesPosition, 0.80, 3);
// Moving hour arm by second increments
var secondsPosition = now.getSeconds() / 60;
drawArm(secondsPosition, 0.90, 1);
};
}
在您的 html 文件中:
var canvas = document.getElementById("canvas1");
// attaching the sketchProc function to the canvas
var processingInstance = new Processing(canvas, sketchProc);