Contents
  1. 1. Processing
  2. 2. canvas

Processing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
float x = 33;
float y = 5;
float velocity = 0.0; //初速度
float radius = 15.0; //半径
float friction = 0.99; //摩擦系数
float acceleration = 0.3; //加速度
void setup(){
size(500, 100); //画布大小
smooth();
noStroke();
ellipseMode(RADIUS);
}
void draw(){
fill(0, 12);
rect(0, 0, width, height);
fill(255);
velocity += acceleration;
velocity *= friction;
y += velocity;
x++;
if (y > (height - radius)) {
y = height - radius;
velocity = -velocity;
}
ellipse(x, y, radius, radius);
}

canvas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<script>
var ball = {x:33, y:15, radius:15.0, acceleration:3, velocity:0, friction:0.98, color:"#005588"}
window.onload = function(){
var canvas = document.getElementById('canvas'); //拿到canvas画布
canvas.width = 1000;
canvas.height = 250;
var context = canvas.getContext("2d"); //取得canvas绘图环境
setInterval( //每50ms执行一次function函数
function(){
render(context);
update();
},50
)
}
function update(){
ball.x += 2;
ball.y += ball.velocity;
ball.velocity *= ball.friction;
ball.velocity += ball.acceleration;
if(ball.y >= canvas.height - ball.radius){
ball.y = canvas.height - ball.radius;
ball.velocity = - ball.velocity;
}
}
function render(cxt){
cxt.clearRect(0 , 0 , cxt.canvas.width , cxt.canvas.height);
cxt.fillStyle = ball.color;
cxt.beginPath();
cxt.arc(ball.x , ball.y , ball.radius , 0 , 2*Math.PI);
cxt.closePath();
cxt.fill()
}
</script>

就从效果上看,Processing的效果比canvas要好的多,而且代码更加直观,更易理解,下次学了d3以后也一同放上来

Contents
  1. 1. Processing
  2. 2. canvas