Reputation: 1384
I am using p5.js to draw a simple line.
function setup() {
//createCanvas(windowWidth, windowHeight);
createCanvas(400, 200);
}
function draw() {
background(255, 255, 255);
fill(255, 0, 0);
stroke(255, 0, 0);
strokeWeight(1);
line(0, 0, 250, 100);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
But the line drawn suddenly at once.
How can I draw the line slowly / gradually? (i.e in 300 milliseconds).
That it looks like animating from point(0,0) to point(250,100).
Upvotes: 1
Views: 1399
Reputation: 1830
FrameRate can be used to adjust the speed of a drawing. This sketch draws a diagonal line that begins slowly at point 0,0 and then speeds up until it reaches point 250, 100.
var x = 0;
function setup() {
createCanvas(400, 200);
frameRate(10);
}
function draw() {
background(255, 255, 255);
fill(255, 0, 0);
stroke(255, 0, 0);
strokeWeight(1);
// y = mx + b
line(0, 0, x, 100/250*x);
x++;
if (x > 50){
frameRate(30);
}
if (x > 250){
noLoop();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
Upvotes: 1
Reputation: 942
I had a quick look at p5 and it looks like it calls the draw
method at intervals. If you want movement to happen you just need to program it.
I've put together a quick example below. I think it's drawing a lot slower than you want but I'm not sure how often p5 calls draw
.
var position = 0,
end = 300;
function setup() {
//createCanvas(windowWidth, windowHeight);
createCanvas(400, 200);
}
function draw() {
background(255, 255, 255);
fill(255, 0, 0);
stroke(255, 0, 0);
strokeWeight(1);
var xEnd = 250,
yEnd = 100;
// Got to the end yet?
if (position < end) {
// Work out positions.
xEnd = (xEnd / end) * position;
yEnd = (yEnd / end) * position;
}
line(0, 0, xEnd, yEnd);
// Increment position.
position++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
Upvotes: 2