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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值