how to animate drawing lines on canvas - javascript

I have created some lines connecting with each other on canvas. Now I want to animate these lines while drawing on canvas.
Can anyone please help?
here is my code and fiddle URL:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(0,0,0,0);
ctx.lineTo(300,100);
ctx.stroke();
ctx.moveTo(0,0,0,0);
ctx.lineTo(10,100);
ctx.stroke();
ctx.moveTo(10,100,0,0);
ctx.lineTo(80,200);
ctx.stroke();
ctx.moveTo(80,200,0,0);
ctx.lineTo(300,100);
ctx.stroke();
http://jsfiddle.net/s4gWK/1/

I understand that your want the lines to extend incrementally along the points in your path using animation.
A Demo: http://jsfiddle.net/m1erickson/7faRQ/
You can use this function to calculate waypoints along the path:
// define the path to plot
var vertices=[];
vertices.push({x:0,y:0});
vertices.push({x:300,y:100});
vertices.push({x:80,y:200});
vertices.push({x:10,y:100});
vertices.push({x:0,y:0});
// calc waypoints traveling along vertices
function calcWaypoints(vertices){
var waypoints=[];
for(var i=1;i<vertices.length;i++){
var pt0=vertices[i-1];
var pt1=vertices[i];
var dx=pt1.x-pt0.x;
var dy=pt1.y-pt0.y;
for(var j=0;j<100;j++){
var x=pt0.x+dx*j/100;
var y=pt0.y+dy*j/100;
waypoints.push({x:x,y:y});
}
}
return(waypoints);
}
Then you can use requestAnimationFrame to animate each incremental line segment:
// calculate incremental points along the path
var points=calcWaypoints(vertices);
// variable to hold how many frames have elapsed in the animation
// t represents each waypoint along the path and is incremented in the animation loop
var t=1;
// start the animation
animate();
// incrementally draw additional line segments along the path
function animate(){
if(t<points.length-1){ requestAnimationFrame(animate); }
// draw a line segment from the last waypoint
// to the current waypoint
ctx.beginPath();
ctx.moveTo(points[t-1].x,points[t-1].y);
ctx.lineTo(points[t].x,points[t].y);
ctx.stroke();
// increment "t" to get the next waypoint
t++;
}

EDIT: I misunderstood your original post. For your situation you do not need to clear the previous animation, only when the animation is complete to start it all over.
jsfiddle : http://jsfiddle.net/Grimbode/TCmrg/
Here are two websites that helped me understand how animations work.
http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/
In this article William speaks sprite animations, which of course isn't what you are interested in. What is interesting is that he uses a recursive loop function created by Paul Irish.
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
This function will attempt to spin 60 times per second (so essentially at 60 fps).
(function() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
So the big question is, how does this work? You pretty much just need to do this:
function gameLoop () {
window.requestAnimationFrame(gameLoop);
renderLine();
}
var counter = 0;
var old_position = {x: 0, y: 0};
var new_position = {x: 0, y: 0};
var width = 10;
var height = 10;
function renderLine(){
/* Here you clear the old line before you draw the new one */
context.clearRect(old_position.x, old_position.y, width, height)
/* you update your new position */
new_position = {x: 100, y: 200};
/* Here you call your normal moveTo and lineTo and stroke functions */
/* update old position with the nwe position */
old_position = new_position;
}
After this step, your question will probably like. "Ok, I have some kind of animation going on, but I don't want my line animation to spin at 60 fps". If you read williams post he uses "ticks".
The websites I linked do a much better job at explaining than I could. I suggest you read up on them. [= I had fun reading them.
AND: Here is your jfiddle :)
http://jsfiddle.net/Grimbode/TCmrg/

The idea is to draw and draw and draw several different lines in a loop to have the illusion that it's "animating". But that is the concept of animation anyway.
So determine what animation you want to do, and find out a way you can draw each frame in a loop.
That's the concept anyway. But I'd advise you use libraries for this.
Fabric.js (http://fabricjs.com/) and KineticJS (http://kineticjs.com/) are the libraries/frameworks I'd point you to.

Related

html canvas animation flickering

I'm in the middle of creating this simple animation using HTML5 Canvas and JavaScript and I'm experiencing a problem with flickering objects.
I was trying to find the solution on the internet before I asked this question and all I found was basically:
avoid loading new image , object at each new frame
use requestAnimationFrame()
I think I've done that all and the flickering is still happening.
(blue rectangles (obstacles) in my case.
The only solution that works is reducing the number of pixels in method responsible for moving the object, here:
obstacle.prototype.moveObstacle = function(){
this.x -=3
}
but the the animation is too slow.
Is there any way around it?
JSFiddle: https://jsfiddle.net/wojmjaq6/
Code:
var cnv = document.getElementById("gameField");
var ctx = cnv.getContext("2d");
var speedY = 1
var obst1 = new obstacle(cnv.width + 50);
var myBird = new bird(100, 1);
function bird(x, y) {
this.x = x;
this.y = y;
this.gravity = 0.3
this.gravitySpeed = 0
}
bird.prototype.drawbird = function() {
ctx.fillStyle = "red"
ctx.fillRect(this.x, this.y, 20, 20);
}
bird.prototype.animate = function() {
this.gravitySpeed += this.gravity
this.y += speedY + this.gravitySpeed
}
function obstacle(x) {
this.x = x;
this.y = 0;
this.obstLen = Math.floor(Math.random() * 400)
}
obstacle.prototype.drawobstacle = function() {
ctx.fillStyle = "blue";
ctx.fillRect(this.x, this.y, 15, this.obstLen)
ctx.fillRect(this.x, cnv.height, 15, -(cnv.height - this.obstLen - 100))
}
obstacle.prototype.moveObstacle = function() {
this.x -= 3
}
function myFun() {
ctx.clearRect(0, 0, cnv.width, cnv.height);
myBird.animate();
myBird.drawbird();
obst1.moveObstacle();
obst1.drawobstacle();
if (obst1.x < 0) {
obst1 = new obstacle(cnv.width + 50);
}
window.requestAnimationFrame(myFun)
};
function test() {
if (myBird.gravity > 0) {
myBird.gravity = -1
} else {
myBird.gravity = 0.3
}
}
document.getElementById("gameField").onmousedown = test
document.getElementById("gameField").onmouseup = test
window.requestAnimationFrame(myFun)
I do see some stuttering with the blue obstacle - the animation is not smooth.
Changing the x position of the obstacle based on the raw requestAnimationFrame loop will not necessarily result in a smooth operation as requestAnimationFrame just requests that the browser re-draws when it can.
The time between calls to requestAnimationFrame can vary depending on the power of the device the animation is on and how much there is to do each frame. There is no guarantee that requestAnimationFrame will give you 60 FPS.
The solutions are to decouple the changing of objects positions with the actual drawing of them, or factor it the elapsed time between frames and calculate the new position based on that to give a smooth animation.
Normally in my canvas animations I just use a library like GreenSock's Animation Platform (GSAP) https://greensock.com/get-started-js which can animate any numeric property over time, then I only have to write code for the drawing part.
It is possible to compute a time based animation in your own requestAnimationFrame, though there is a bit of complexity involved. This looks like a good tutorial on it http://www.javascriptkit.com/javatutors/requestanimationframe.shtml
Cheers,
DouG

Animating a curved motion of an object with svg.js

I want to animate a curved motion (no rotation) of an object by using svg.js. But I can't find any easy solution for this problem. I wrote two little functions which work fine, but it isn't working like a normal animation, and it doesn't run perfectly in the background.
I would prefer some solution like this:
var draw = SVG("drawing").size(500,500);
var rect = draw.rect(50,50);
rect.animate().curvedmove(100,100);
The two functions I made:
function animateJump(object,start,end,ampl,y,i=0){
var speed = 25;
var pos = 0;
pos = start+i*((end-start)/speed);
object.animate(1).move(pos,y+bounceFunction(start,end,ampl,pos));
if (i <= speed){
animateJump(object,start,end,ampl,y,i+1)
}
}
function bounceFunction(a,b,c,x){
return -1 * (x-a)*(x-b) * c * (4/((a-b)*(b-a)));
}
Is there some easy solution?
Thanks for any help!
The animate method establish a new animation context in which runs the timer you specified (1 sec by default). So if you do el.animate().move(100,100) the element will move to position 100,100 in 1 second.
However, if you want to use your own function you need to listen to the during event which gives you the current position from 0-1 in time.
el.animate().during(function(pos, morphFn, easedPos) {
this.move(pos, bounceFunction(pos))
})
Note that pos is a value between 0 and 1 so setting it directly as coordinate does not make that much sense. You need to figure our the start and end value of the move and calculate it yourself (or use the morphFn like morphFn(start, end))
Example:
var startX = 100
var endX = 300
var startY = 100
var endY = 300
el.animate().during(function(pos, morphFn, easedPos) {
var x = morphFn(startX, endX)
var y = SVG.morph(bounceFunction(pos))(startY, endY)
this.move(x, y)
})
the morphFn is by default bound to the current position. So if you have your own position (like when using your custom bounce function) you need to create a new morph function which you can do with the SVG.morph method. This method expects a position and gives back a morph function bound to this positon.
So this would be the same:
var x = SVG.Morph(pos)(startX, endX)
var y = SVG.Morph(bounceFunction(pos))(startY, endY)

Javascript canvas animation. Moving, growing and fading object

Working on a project and cannot seem to get my animation right. I will not be showing the code because it simply doesn't work but it would be cool if someone were to give me a few pointers on how to animate a cloud of smoke moving upwards while slowly fading and increasing in size.
This effect should technically repeat once the y value reaches 0 i.o.w. the cloud reaches the top of the canvas.
What I need to know is how do I animate this, and which methods do I use. This is a kind of a self learning assignment.
Thanks in advance.
Here is a Plunker example of sprites growing in size and fading in transparency.
It is done using Pixi.js which actually renders in webgl with a canvas fallback. It should be possible to take the algorithm and apply it to raw canvas (although it would take some work).
var insertAfter = function(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var range = function(aCount) {
return new Array(aCount)
}
function main() {
var el_main = document.getElementById("animation_main");
var el_div = document.createElement('div');
el_div.setAttribute('id', 'main_stage');
insertAfter(el_div, el_main);
renderer = PIXI.autoDetectRenderer(300, 300, {
transparent: true,
antialias: true
});
el_div.appendChild(renderer.view);
window.stage = new PIXI.Container();
window.stage.x = 0;
window.stage.y = 0;
renderer.render(window.stage);
var s = [];
for (x of range(400)) {
tCircle = new PIXI.Graphics();
tCircle.beginFill(0x000000, 1);
tCircle.s = (Math.random() * 2) + 1;
tCircle.drawCircle(0, 0, 5 - tCircle.s);
tCircle.x = Math.random() * 300
tCircle.y = (Math.random() * 50) + 20
tCircle.endFill();
s.push(tCircle);
window.stage.addChild(tCircle)
}
window.t = 0
animate = function(t) {
d = t - window.t
window.t = t
//Animation Start
for (n in s){
s[n].x += ((s[n].s / 25) * d)
s[n].alpha = 1 - s[n].x / 300
s[n].scale.x = 1 - s[n].alpha
s[n].scale.y = 1 - s[n].alpha
if (s[n].x > 300) {
s[n].x = 0
s[n].y = (Math.random() * 50) + 20
}
}
renderer.render(window.stage)
//Animation End
requestAnimationFrame(animate);
}
requestAnimationFrame(animate)
}
document.addEventListener("DOMContentLoaded", function(e){
main();
});
At the moment all of the tweening is linear ... it might look more realistic with a logarithmic or exponential tween ... but for simplicity i just left it as linear.
Jakob Jenkov has done a really nice on-line book about canvas here:
http://tutorials.jenkov.com/html5-canvas/index.html
Since yours is a learning experience, I would just point you towards:
The basic workflow of html5 Canvas: Anything drawn on the canvas cannot be altered, so all canvas animation requires repeatedly doing these things in an animation loop: (1) clearing the canvas, (2) calculating a new position for your objects, and (3) redrawing the objects in their new positions.
Animations: requestAnimationFrame as a timing loop: http://blog.teamtreehouse.com/efficient-animations-with-requestanimationframe
Transformations: Canvas gives you the ability to scale, rotate and move the origin of its drawing surface.
Styling: Canvas provides all the essential styling tools for drawing--including globalAlpha which sets opacity.

How to paint over a complex object

I do have a fairly complex figure painted on canvas. (~ 1000 polygons). The repainting time for all of them is about 1 sec (very slow). Now I need to let user move over that figure and display a vertical and horizontal lines (cross hairs) from under mouse position. What is the best technique to paint only those 2 lines without going over all polygons and repaint everything at every mouse move.
Thx
This answer is broken.
You want to draw lines and move them without touching the underlying painting.
In the good old days, the method used was to paint with xor composition on top of the drawing, and draw the same pattern (here it would be lines) the same way at the same location to remove it from the screen, again without touching the real painting.
I tried to use this method with the code below to test it out, but it doesn't seem to work. Hopefully, someone with a better knowledge of canvas and js will come forth and fix things up.
function onmousemove(e){
// firt run
var tcanvas = document.getElementById("testCanvas");
var tcontext = tcanvas.getContext("2d");
var pos = {x : e.clientX, y : e.clientY,
w : tcanvas.width, h : tcanvas.height };
var comp = tcontext.globalCompositeOperation;
var paintline = function (p){
tcontext.save();
tcontext.lineWidth = 1;
tcontext.globalCompositeOperation = 'xor';
tcontext.fillStyle = "#000000";
tcontext.moveTo(0,p.y);
tcontext.lineTo(p.w,p.y);
tcontext.moveTo(p.x,0);
tcontext.lineTo(p.x,p.h);
tcontext.stroke();
tcontext.restore();
};
tcontext.save();
paintline(pos);
tcontext.restore();
var next = function(e){
var comp = tcontext.globalCompositeOperation;
paintline(pos);
pos = {x : e.clientX, y : e.clientY,
w : tcanvas.width, h : tcanvas.height };
paintline(pos);
};
document.onmousemove = next;
}
(function draw_stuff(){
// setup canvas
var tcanvas = document.getElementById("testCanvas");
var tcontext = tcanvas.getContext("2d");
// draw square
tcontext.fillStyle = "#FF3366";
tcontext.fillRect(15,15,70,70);
// set composite property
tcontext.globalCompositeOperation = 'xor';
// draw text
tcontext.fillStyle="#0099FF";
tcontext.font = "35px sans-serif";
tcontext.fillText("test", 22, 25);
// draw circle
tcontext.fillStyle = "#0099FF";
tcontext.beginPath();
tcontext.arc(75,75,35,0,Math.PI*2,true);
tcontext.fill();
document.onmousemove = onmousemove;
})();
Also, there are problem with compositing depending on the browser.

Animating sprite frames in canvas

I'm making a small platform game with the canvas element and I'm having trouble working out the best way to use sprites.
Canvas doesn't support animated GIFs, so I can't do that, so instead I made a film strip for my animated sprites to give the illusion that a character is moving. Like this: http://i.imgur.com/wDX5R.png
Here's the relevant code:
function player() {
this.idleSprite = new Image();
this.idleSprite.src = "/game/images/idleSprite.png";
this.idleSprite.frameWidth = 28;
this.idleSprite.frameHeight = 40;
this.idleSprite.frameCount = 12;
this.runningSprite = new Image();
this.runningSprite.src = "/game/images/runningSprite.png";
this.runningSprite.frameWidth = 34;
this.update = function() {
}
var frameCount = 1;
this.draw = function() {
c.drawImage(this.idleSprite, this.idleSprite.frameWidth * frameCount, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, 0, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
if(frameCount < this.idleSprite.frameCount - 1) { frameCount++; } else { frameCount = 0; }
}
}
var player = new player();
As you can see, I'm defining the idle sprite and also its frame width and frame count. Then in my draw method, I'm using those properties to tell the drawImage method what frame to draw. Everything works fine, but I'm unhappy with the frameCount variable defined before the draw method. It seems... hacky and ugly. Would there be a way that people know of to achieve the same effect without keeping track of the frames outside the draw method? Or even a better alternative to drawing animated sprites to canvas would be good.
Thanks.
You could select the frame depending on some fraction of the current time, e.g.
this.draw = function() {
var fc = this.idleSprite.frameCount;
var currentFrame = 0 | (((new Date()).getTime()) * (fc/1000)) % fc;
c.drawImage(this.idleSprite, this.idleSprite.frameWidth * currentFrame, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, 0, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
}
That will give you animation with a period of one second (the 1000 is a millisecond value). Depending on your frame rate and animation this might look jerky, but it doesn't rely on persistent counters.

Categories

Resources