timed rectangle animation javascript - javascript

I want to create a game where I need a animation: First should drawed a rectangle after 5 seconds, the second rect after 5 seconds, the third after 5 too, the fourth after 5 too, the 6-10 rects after 4s, the 10-15 rects after 3s, the 15-20 rects after 2s and the 20-25 rects after 1 second. The rectangles came from above and should run with a speed called recty to the bottom. Maybe will this help:jsfiddle.
var x = canvasWidth / 100;
var y = canvasHeight / 100;
b = 5000;
function init() {
recty = canvasHeight / 100 * 20;
rectx = (Math.random() *(x * 50)) + (x / 5);
rectb = (Math.random() * (x * 40)) + x * 20;
return setInterval(main_loop, 10);
}
function draw() {
rectheight = canvasHeight / 100 * 10;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// draw triangles
ctx.beginPath();
ctx.moveTo(x * 90, y * 50);
ctx.lineTo(x * 99, y * 60);
ctx.lineTo(x * 99, y * 40);
ctx.closePath();
ctx.stroke();
}
function drawrect() {
// draw rect
ctx.beginPath();
fillStyle = "#000000";
ctx.rect(rectx, recty, rectb, rectheight);
ctx.fill();
}
function update() {
recty += 1;
if (recty > canvasHeight) {
recty = -rectheight;
rectx = (Math.random() *(x * 50)) + (x / 5);
rectb = (Math.random() *(x * 50)) + (x / 5);
b -=1000;
}
if (recty > canvasHeight) {
recty -= 1;
}
}
function main_loop() {
draw();
update();
collisiondetection();
drawrect();
}
init();
setInterval ( drawrect, b );

Modern browsers have a built-in timer: requestAnimationFrame.
A requestAnimationFrame loop will fire about every 16ms and will be given a very precise currentTime argument. You start the timing loop with: requestAnimationFrame(Timer);. The loop will execute only once for each requestAnimationFrame you issue, so you put a requestAnimationFrame inside the loop itself to keep it running.
Here's an example timing loop that calculates the elapsed time since the timing loop started:
// variable used to calculate elapsed time
var lastTime;
// start the first timing loop
requestAnimationFrame(Timer);
function Timer(time){
// request another timing loop
// Note: requestAnimationFrame fires only once,
// so you must request another loop inside
// each current loop
requestAnimationFrame(Timer);
// if this is the very first loop, initialize `lastTime`
if(!lastTime){lastTime=time;}
// calculate elapsed time since the last loop
var elapsedTime=time-lastTime;
}
To make your rectangles "time aware" you can create a javascript object for each rectangle that defines all that's need to draw that rectangle at the desired timing interval. Then use this javascript object to draw the rectangle at the desired position after the desired time interval.
Example of rectangle object properties
position of the rect: x,y
the time interval to wait before next updating the rect's position: interval
the distance to move the rect during an update: moveByX, moveByY
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var rects=[]
rects.push({x:10,y:10,moveByX:5,interval:500,nextMoveTime:0});
rects.push({x:10,y:50,moveByX:5,interval:1000,nextMoveTime:0});
rects.push({x:10,y:110,moveByX:5,interval:2000,nextMoveTime:0});
var isFirstLoop=true;
// start the timing loop
requestAnimationFrame(Timer);
function Timer(currentTime){
// request another timing loop
// Note: requestAnimationFrame fires only once,
// so you must request another loop inside
// each current loop
requestAnimationFrame(Timer);
if(isFirstLoop){
isFirstLoop=false;
for(var i=0;i<rects.length;i++){
rects[i].nextMoveTime=time+rects[i].interval;
}
}
ctx.clearRect(0,0,cw,ch);
for(var i=0;i<rects.length;i++){
drawRect(rects[i],currentTime);
}
}
function drawRect(r,time){
if(time>r.nextMoveTime){
r.x+=r.moveByX;
r.nextMoveTime=parseInt(time+r.interval);
}
ctx.strokeRect(r.x,r.y,110,15);
ctx.fillText('I move every '+r.interval+'ms',r.x+5,r.y+10);
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

Have you though about css animation?
It can come really handy, and has a better performance than javascript.
You can use transitions on position, and even delay if you don't care about IE9 and before. If you do, you should initiate the animations with javascript by adding a class to each boxes, and that would make it cross-browser.
Bassic css mockup for this would look something like this:
.box{
width:90px;height:90px;background:red;position:absolute;
-webkit-animation: mymove 5s; /* Chrome, Safari, Opera */
animation: mymove 5s;
animation-delay: 2s;
-webkit-animation-delay: 2s; /* Chrome, Safari, Opera */
}
And then you can add rules for specific boxes, and overrule the basic box style.
.box-1{animation-delay:10s; -webkit-animation-delay: 2s;}
See jsfiddle: http://jsfiddle.net/eyqtg9wp/

Related

canvas - how to set interval in requestAnimationFrame() loop?

i was looking for how to stop a loop in requestAnimationFrame() loop.
I'm trying to make a simple top-to-bottom falling circle animation and every time the circle hit the bottom, in this case the window.innerHeight, it will set its position back to its starting position then wait until 12 sec to animate again. i'm trying to use setTimeOut() but the circle got faster instead.
this is my code:
drawCircle = () =>
{
requestAnimationFrame(this.drawCircle);
this._CONTEXT.clearRect(0, 0, this._CANVAS.width, this._CANVAS.height);
this._CONTEXT.beginPath();
this._CONTEXT.arc(this.x, this.y, 20, 0, 2 * Math.PI);
this._CONTEXT.lineWidth = 1;
this._CONTEXT.fillStyle = '#ff0000';
this._CONTEXT.fill();
this.y += 15;
if (this.y > this._CANVAS.height) {
setTimeout(12000);
this.initPos();
}
}

HTML Canvas: Animation Delay

Here is a demo of my Canvas.
The canvas generates a random rectangle and animates it by scaling it from 1.0 to 1.2 and back to 1.0 again. (Kinda like a human heart). This animation takes approximately 2 seconds to complete. There are 60 totalIterations. It starts with 0 and increments by one for every frame until it reaches 60. Once it reaches 60, the iteration is set back to 0 and animates from 1.2 scale back to 1.0.
What I want to do is before the execution of the next cycle (cycle meaning from 1.0 scale, to 1.2, and back to 1.0), I want to defer the scale.
Here is what I tried to do:
Context:
this.intermission = 3; // time to wait, or "defer" for
elapsed = (Date.now() - this.initTime) / 1000; // time elapsed since initialization (in seconds)
Condition:
if((elapsed % this.intermission >= (this.intermission - (this.intermission-1))) && (elapsed % this.intermission <= (this.intermission + (this.intermission-1)))) {
ctx.scale(this.easing, this.easing);
}
Condition Explained (Probably makes no sense):
If the remainder from dividing the elapsed time by 3 is greater than or equal to 2 AND the remainder from dividing the elapsed time by 3 is less than or equal to 5, scale the rectangle using the ease function.
... I wanted to give it some "buffer" room to complete the animation
If I were to increase the intermission to 10, the above condition would not work anymore, so I need a much better solution.
I thought about using setTimeout(function(){...}, x), but this is inside the JavaScript class.
Animation Lists / Stacks.
Keyframing
The best way would be to set up code to manage keyframes so you could just create a list of keyframes for each property of an object you wish to change over time. This allows you to create very complex animations that can be serialized to a JSON file. This decouples the animation from the code, but requires a lot more code.
Animation List
If it is just a simple animation then you can create an animation stack (or list if animation order is static), which is just a set of functions that get called in turn for each part of the animation.
You set a startTime for each part of the animation, being careful to set it consistently so you do not get any time drift. If the animation cycle is 4 seconds long then it should repeat every 4 seconds and in 4,000,000 seconds it should be just as precise.
Always use requestAnimationFrame (rAF) when animating anything on the page. rAF calls the callback passing as the first argument the time in ms (1/1000th) with a precision of 1/1,000,000 (0.001ms).
Endless animation using animation list
const canvas = document.createElement("canvas");
canvas.height = canvas.width = 300;
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas)
// ease function
function easeInOut(x, pow = 2) {
x = x < 0 ? 0: x > 1 ? 1 : x;
var xx = Math.pow(x,pow);
return xx/(xx+Math.pow(1-x,pow));
};
function MyObj(){
this.x = 100;
this.y = 100;
this.size = 40;
this.scale = 1;
}
MyObj.prototype = {
getUnitTime(duration){ // get the unit time
var unitTime = (globalTime - startTime) / duration;
if(unitTime >= 1){ // if over time
unitTime = 1; // make sure that the current frame is not over
startTime = startTime + duration; // next frame start (could be in the past)
currentAnim += 1; // next animation in the list
}
return unitTime;
},
grow(){
drawText("Grow 1s");
// grow for 1 second
this.scale = easeInOut(this.getUnitTime(1000)) * 0.6 + 1;
},
shrink(){
drawText("Shrink 1s");
// shrink for 1 second
this.scale = 1.6 - easeInOut(this.getUnitTime(1000)) * 0.6 ;
},
wait(){
drawText("Wait 2s");
this.getUnitTime(2000); // wait two seconds
},
draw(ctx){
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(this.x, this.y, this.size * this.scale, 0, Math.PI * 2);
ctx.fill();
}
}
function drawText(text){
ctx.fillStyle = "black";
ctx.fillText(text,100,36);
}
var obj = new MyObj(); // create the object
// holds the animation list
const animationList = [
obj.grow.bind(obj), // bind the function calls to the object
obj.shrink.bind(obj),
obj.wait.bind(obj)
];
var currentAnim; // index of current animation
var startTime; // start time of current animation
var globalTime; // time from the requestAnimationFrame callback argument
ctx.font = "32px arial";
ctx.textAlign = "center";
// main animation loop
function update(time){
globalTime = time; // set the global
if(currentAnim === undefined){ // if not set then
startTime = time; // set start time
currentAnim = 0; // set the index of the first animation
}
// clear the screen
ctx.clearRect(0,0,canvas.width,canvas.height);
// call the animation function
animationList[currentAnim % animationList.length]();
// draw the object
obj.draw(ctx);
// request next frame
requestAnimationFrame(update);
}
// start it all happening
requestAnimationFrame(update);
Stacks
Stacks are much the same but used when the animation is conditional. You use some event to push the animation functions onto the stack. Then you shift the animation functions from the stack as needed. Or you may want the animation to repeat 10 times, then do something else, then start again. The animation stack lets you do this rather than have a huge list of animations.
Stack example using click event.
const canvas = document.createElement("canvas");
canvas.height = canvas.width = 300;
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas)
// ease function
function easeInOut(x, pow = 2) {
x = x < 0 ? 0: x > 1 ? 1 : x;
var xx = Math.pow(x,pow);
return xx/(xx+Math.pow(1-x,pow));
};
function MyObj(){
this.x = 100;
this.y = 100;
this.size = 40;
this.scale = 1;
}
MyObj.prototype = {
getUnitTime(duration){ // get the unit time
var unitTime = (globalTime - startTime) / duration;
if(unitTime >= 1){ // if over time
unitTime = 1; // make sure that the current frame is not over
startTime = startTime + duration; // next frame start (could be in the past)
currentAnim = undefined
}
return unitTime;
},
grow(){
drawText("Grow 1s");
// grow for 1 second
this.scale = easeInOut(this.getUnitTime(1000)) * 0.6 + 1;
},
shrink(){
drawText("Shrink 1s");
// shrink for 1 second
this.scale = 1.6 - easeInOut(this.getUnitTime(1000)) * 0.6 ;
},
timeup(){
drawText("Click to Animate");
currentAnim = undefined;
},
draw(ctx){
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(this.x, this.y, this.size * this.scale, 0, Math.PI * 2);
ctx.fill();
}
}
function drawText(text){
ctx.fillStyle = "black";
ctx.fillText(text,100,36);
}
var obj = new MyObj(); // create the object
// holds the animation list
const animationStack = [obj.timeup.bind(obj)];
var currentAnim; // index of current animation
var startTime; // start time of current animation
var globalTime; // time from the requestAnimationFrame callback argument
ctx.font = "26px arial";
ctx.textAlign = "center";
function startAnim(){
animationStack.length = 0;
animationStack.push(obj.grow.bind(obj));
animationStack.push(obj.shrink.bind(obj));
animationStack.push(obj.timeup.bind(obj));
if(currentAnim === undefined){// only restart if animation is not running
requestAnimationFrame(update);
}
startTime = undefined;
currentAnim = undefined;
}
canvas.addEventListener("click",startAnim)
// main animation loop
function update(time){
globalTime = time; // set the global
if(startTime === undefined){ // if not set then
startTime = time; // set start time
}
if(currentAnim === undefined){
if(animationStack.length > 0){
currentAnim = animationStack.shift();
}
}
if(currentAnim === undefined){
return;
}
// clear the screen
ctx.clearRect(0,0,canvas.width,canvas.height);
// call the animation function
currentAnim();
// draw the object
obj.draw(ctx);
// request next frame
requestAnimationFrame(update);
}
// start it all happening
requestAnimationFrame(update);

HTML5 Canvas alpha transparency doesn't work in firefox for curves when window is big

I'm drawing a curve on an HTML5 canvas and am using alpha transparency to create a glow effect, by drawing a thicker version of the curve underneath with an alpha of less than 1, then drawing a thinner version of the curve on top (and I'm doing this with several levels of recursion).
Okay here's the problem. It works exactly the way I want it to in Chrome, giving a beautiful glow effect. But in Firefox, the alpha doesn't render properly if my browser dimensions are bigger than around 300px in height (yes that sounds crazy but it is actually what it is doing for some reason). If I resize my browser to be extremely tiny, then all the sudden the alpha works and I get my awesome glow. Once I make the window a reasonable size, the alpha no longer works so instead of a glowing line I just get a really thick line. :( Code is below.
HTML:
<body>
<canvas id="viewport">
<script type="text/javascript" src="scripts/render.js"></script>
</body>
CSS:
* {
background-color:#000000;
padding:0px;
margin:0px;
width:100%;
height:100%;
overflow:hidden;
}
#viewport {
border:0px;
}
Javascript:
window.viewport = document.getElementById("viewport");
window.context = viewport.getContext("2d");
window.xFactor = 1;
window.yFactor = 1;
function initializeViewport() {
maximizeViewport();
setFactors();
}
function maximizeViewport() {
viewport.width = window.innerWidth;
viewport.height = window.innerHeight;
}
function setFactors() {
xFactor = window.innerWidth / 100;
yFactor = window.innerHeight / 100;
}
function absX(x) {
return Math.floor(x * xFactor);
}
function absY(y) {
return Math.floor(y * yFactor);
}
function drawQuadraticCurve(startX, startY, controlX, controlY, endX, endY, lineWidth, gradient, alpha, glowiness, glowLevel) {
glowLevel = (typeof glowLevel === 'undefined') ? 0 : glowLevel;
// Draw the glow first
if (glowLevel < glowiness) {
drawQuadraticCurve(startX, startY, controlX, controlY, endX, endY, lineWidth + Math.sqrt(glowLevel), gradient, alpha*0.65, glowiness, glowLevel + 1);
}
// Then draw the curve
context.beginPath();
context.moveTo(absX(startX), absY(startY));
context.quadraticCurveTo(absX(controlX), absY(controlY), absX(endX), absY(endY));
context.lineWidth = lineWidth;
context.strokeStyle = gradient;
context.globalAlpha = alpha;
context.shadowColor = "#FFFFFF";
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.stroke();
}
function createRadialGradient(colors, innerX, innerY, innerR, outerX, outerY, outerR) {
var gradient = context.createRadialGradient(absX(innerX),absY(innerY),Math.min(absX(innerR/2), absY(innerR/2)),absX(outerX),absY(outerY),Math.min(absX(outerR/2), absY(outerR/2)));
var gradientLength = colors.length;
for (i=0; i<gradientLength; i++) {
gradient.addColorStop(colors[i][0], colors[i][1]);
}
return gradient;
}
initializeViewport();
drawQuadraticCurve(80,65,20,70,70,10, 1,createRadialGradient([[0,"#FFFFFF"],[0.7,"#33CCFF"],[1,"#9944FF"]],50,50,1,50,50,90),1,8,0);
Screenshot of it working in Chrome: http://i.imgur.com/brVT2i6.png
Screenshot of it NOT working in Firefox: http://i.imgur.com/63Z4PJY.png
Screenshot of it working in Firefox after I've resized the window to be ridiculously small: http://i.imgur.com/d9AihEu.png
First working solution gets an upvote and a green checkmark! Yay!
Here is a glowing quadratic curve made up of small, individual line segments--each segment being a different color. A shadowColor equal to the segment color causes the glow. The rendering is compatible across browsers (including FF).
(You can control the linewidth and the glow strength)
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// variables to define colors -- use hsl instead of rgb
var hue=10;
var hueShift=4;
// define the quadratic curve
var startPt={x:350,y:100};
var controlPt={x:0,y:250};
var endPt={x:350,y:400};
// variables defining the starting & ending point of
// the current line segment.
var newXY=startPt;
var oldXY=startPt;
// the current interval along the quadratic curve
// (used to calc an x,y along the curve)
// (t is kind-of like a percentage along the curve--kind of but not)
var t=0;
// the unshadowed linewidth
ctx.lineWidth=1;
// the shadow to apply around the line
ctx.shadowBlur=7;
// round the endcaps to visually blend the line segments
ctx.lineCap='round';
// start with a black-filled canvas
ctx.fillStyle='black';
ctx.fillRect(0,0,cw,ch);
// start the animation
requestAnimationFrame(animate);
function animate(time){
// calculate a new x,y along the curve
var T=t/100;
var newXY=getQuadraticBezierXYatT(startPt,controlPt,endPt,T);
// change the color for this segment
hue=(hue+hueShift)%360;
// draw this line segment with a shadow-glow
glowLine(oldXY,newXY,hue);
// set old=new in preparation for the next loop
oldXY=newXY;
// request another animation loop intil reaching 100
if(++t<100){
requestAnimationFrame(animate);
}
}
function glowLine(oldXY,newXY,hue){
// calculate the hsl color given the new hue
var hsl="hsl(" + (hue % 360) + ",99%,50%)";
// draw a glowing line segment
// (==a line segment with a shadow of the same color as the line segment)
ctx.beginPath();
ctx.moveTo(oldXY.x,oldXY.y);
ctx.lineTo(newXY.x,newXY.y);
ctx.fillStyle= hsl
ctx.strokeStyle=hsl;
ctx.shadowColor=hsl;
// overdraw the line segment so it really stands out
for(var i=0;i<6;i++){
ctx.stroke();
}
}
// calculate an [x,y] along a quadratic curve given an interval T
function getQuadraticBezierXYatT(startPt,controlPt,endPt,T) {
var x = Math.pow(1-T,2) * startPt.x + 2 * (1-T) * T * controlPt.x + Math.pow(T,2) * endPt.x;
var y = Math.pow(1-T,2) * startPt.y + 2 * (1-T) * T * controlPt.y + Math.pow(T,2) * endPt.y;
return( {x:x,y:y} );
}
body{ background-color:ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=500 height=500></canvas>
This is really a comment, but it wouldn't fit in the space allocated to a comment. :-)
I've consulted the All-Knowing-Oracle of Html5 Canvas--the w3.org.
If you assign a zero shadowBlur (as you do) the spec says there should be no shadow applied.
That means that FF with the larger canvas size is correctly applying the w3 standard (not drawing any shadow) and both Chrome & FF(smaller version) are incorrectly applying a shadow when it should not.
http://www.w3.org/TR/2dcontext/
Shadows are only drawn if the opacity component of the alpha component
of the color of shadowColor is non-zero and either the shadowBlur is
non-zero, or the shadowOffsetX is non-zero, or the shadowOffsetY is
non-zero.
Therefore, to have cross-browser compatibility, you mustn't rely on quirks in the rendering when shadowBlur=0. You must create your glow in another way within the "rules".

Handdrawn circle simulation in HTML 5 canvas

The following code creates a circle in HTML 5 Canvas using jQuery:
Code:
//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");
DrawCircle(75, 75, 20);
//draw a circle
function DrawCircle(x, y, radius)
{
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI*2, true);
ctx.fillStyle = 'transparent';
ctx.lineWidth = 2;
ctx.strokeStyle = '#003300';
ctx.stroke();
ctx.closePath();
ctx.fill();
}
I am trying to simulate any of the following types of circles:
I have researched and found this article but was unable to apply it.
I would like for the circle to be drawn rather than just appear.
Is there a better way to do this? I'm sensing there's going to be a lot of math involved :)
P.S. I like the simplicity of PaperJs, maybe this would be the easiest approach using it's simplified paths?
There are already good solutions presented here. I wanted to add a variations of what is already presented - there are not many options beyond some trigonometry if one want to simulate hand drawn circles.
I would first recommend to actually record a real hand drawn circle. You can record the points as well as the timeStamp and reproduce the exact drawing at any time later. You could combine this with a line smoothing algorithm.
This here solution produces circles such as these:
You can change color, thickness etc. by setting the strokeStyle, lineWidth etc. as usual.
To draw a circle just call:
handDrawCircle(context, x, y, radius [, rounds] [, callback]);
(callback is provided as the animation makes the function asynchronous).
The code is separated into two segments:
Generate the points
Animate the points
Initialization:
function handDrawCircle(ctx, cx, cy, r, rounds, callback) {
/// rounds is optional, defaults to 3 rounds
rounds = rounds ? rounds : 3;
var x, y, /// the calced point
tol = Math.random() * (r * 0.03) + (r * 0.025), ///tolerance / fluctation
dx = Math.random() * tol * 0.75, /// "bouncer" values
dy = Math.random() * tol * 0.75,
ix = (Math.random() - 1) * (r * 0.0044), /// speed /incremental
iy = (Math.random() - 1) * (r * 0.0033),
rx = r + Math.random() * tol, /// radius X
ry = (r + Math.random() * tol) * 0.8, /// radius Y
a = 0, /// angle
ad = 3, /// angle delta (resolution)
i = 0, /// counter
start = Math.random() + 50, /// random delta start
tot = 360 * rounds + Math.random() * 50 - 100, /// end angle
points = [], /// the points array
deg2rad = Math.PI / 180; /// degrees to radians
In the main loop we don't bounce around randomly but increment with a random value and then increment linearly with that value, reverse it if we are at bounds (tolerance).
for (; i < tot; i += ad) {
dx += ix;
dy += iy;
if (dx < -tol || dx > tol) ix = -ix;
if (dy < -tol || dy > tol) iy = -iy;
x = cx + (rx + dx * 2) * Math.cos(i * deg2rad + start);
y = cy + (ry + dy * 2) * Math.sin(i * deg2rad + start);
points.push(x, y);
}
And in the last segment we just render what we have of points.
The speed is determined by da (delta angle) in the previous step:
i = 2;
/// start line
ctx.beginPath();
ctx.moveTo(points[0], points[1]);
/// call loop
draw();
function draw() {
ctx.lineTo(points[i], points[i + 1]);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(points[i], points[i + 1]);
i += 2;
if (i < points.length) {
requestAnimationFrame(draw);
} else {
if (typeof callback === 'function')
callback();
}
}
}
Tip: To get a more realistic stroke you can reduce globalAlpha to for example 0.7.
However, for this to work properly you need to draw solid to an off-screen canvas first and then blit that off-screen canvas to main canvas (which has the globalAlpha set) for each frame or else the strokes will overlap between each point (which does not look good).
For squares you can use the same approach as with the circle but instead of using radius and angle you apply the variations to a line. Offset the deltas to make the line non-straight.
I tweaked the values a little but feel free to tweak them more to get a better result.
To make the circle "tilt" a little you can first rotate the canvas a little:
rotate = Math.random() * 0.5;
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(-rotate);
ctx.translate(-cx, -cy);
and when the loop finishes:
if (i < points.length) {
requestAnimationFrame(draw);
} else {
ctx.restore();
}
(included in the demo linked above).
The circle will look more like this:
Update
To deal with the issues mentioned (comment fields too small :-) ): it's actually a bit more complicated to do animated lines, especially in a case like this where you a circular movement as well as a random boundary.
Ref. comments point 1: the tolerance is closely related to radius as it defined max fluctuation. We can modify the code to adopt a tolerance (and ix/iy as they defines how "fast" it will variate) based on radius. This is what I mean by tweaking, to find that value/sweet-spot that works well with all sizes. The smaller the circle the smaller the variations. Optionally specify these values as arguments to the function.
Point 2: since we're animating the circle the function becomes asynchronous. If we draw two circles right after each other they will mess up the canvas as seen as new points are added to the path from both circles which then gets stroked criss-crossed.
We can get around this by providing a callback mechanism:
handDrawCircle(context, x, y, radius [, rounds] [, callback]);
and then when the animation has finished:
if (i < points.length) {
requestAnimationFrame(draw);
} else {
ctx.restore();
if (typeof callback === 'function')
callback(); /// call next function
}
Another issues one will run into with the code as-is (remember that the code is meant as an example not a full solution :-) ) is with thick lines:
When we draw segment by segment separately canvas does not know how to calculate the butt angle of the line in relation to previous segment. This is part of the path-concept. When you stroke a path with several segments canvas know at what angle the butt (end of the line) will be at. So here we to either draw the line from start to current point and do a clear in between or only small lineWidth values.
When we use clearRect (which will make the line smooth and not "jaggy" as when we don't use a clear in between but just draw on top) we would need to consider implementing a top canvas to do the animation with and when animation finishes we draw the result to main canvas.
Now we start to see part of the "complexity" involved. This is of course because canvas is "low-level" in the sense that we need to provide all logic for everything. We are basically building systems each time we do something more with canvas than just draw simple shapes and images (but this also gives the great flexibility).
Here are some basics I created for this answer:
http://jsfiddle.net/Exceeder/TPDmn/
Basically, when you draw a circle, you need to account for hand imperfections. So, in the following code:
var img = new Image();
img.src="data:image/png;base64,...";
var ctx = $('#sketch')[0].getContext('2d');
function draw(x,y) {
ctx.drawImage(img, x, y);
}
for (var i=0; i<500; i++) {
var radiusError = +10 - i/20;
var d = 2*Math.PI/360 * i;
draw(200 + 100*Math.cos(d), 200 + (radiusError+80)*Math.sin(d) );
}
Pay attention how vertical radiusError changes when the angle (and the position) grows. You are welcome to play with this fiddle until you get a "feel" what component does what. E.g. it would make sense to introduce another component to radiusError that emulates "unsteady" hand by slowly changing it my random amounts.
There are many different ways to do this. I choose trig functions for the simplicity of the simulation, as speed is not a factor here.
Update:
This, for example, will make it less perfect:
var d = 2*Math.PI/360 * i;
var radiusError = +10 - i/20 + 10*Math.sin(d);
Obviously, the center of the circle is at (200,200), as the formula for drawing a circle (rather, ellipsis with vertical radius RY and horizontal radius RX) with trigonometric functions is
x = centerX + RX * cos ( angle )
y = centerY + RY * sin ( angle )
Your task seems to have 3 requirements:
A hand-drawn shape.
An “organic” rather than “ultra-precise” stroke.
Revealing the circle incrementally instead of all-at-once.
To get started, check out this nice on-target demo by Andrew Trice.
This amazing circle is hand drawn by me (you can laugh now...!)
Andrew's demo does steps 1 and 2 of your requirements.
It lets you hand draw a circle (or any shape) using an organic looking “brush effect” instead of the usual ultra-precise lines normally used in canvas.
It achieves the “brush effect” by by repeated drawing a brush image between hand drawn points
Here’s the demo:
http://tricedesigns.com/portfolio/sketch/brush.html#
And the code is available on GitHub:
https://github.com/triceam/HTML5-Canvas-Brush-Sketch
Andrew Trice’s demo draws-and-forgets the lines that make up your circle.
Your task would be to impliment your third requirement (remembering strokes):
Hand draw a circle of your own,
Save each line segment that makes up your circle in an array,
“Play” those segements using Andrew’s stylized brush technique.
Results: A hand-drawn and stylized circle that appears incrementally instead of all at once.
You have an interesting project…If you feel generous, please share your results!
See live demo here. Also available as a gist.
<div id="container">
<svg width="100%" height="100%" viewBox='-1.5 -1.5 3 3'></svg>
</div>
#container {
width:500px;
height:300px;
}
path.ln {
stroke-width: 3px;
stroke: #666;
fill: none;
vector-effect: non-scaling-stroke;
stroke-dasharray: 1000;
stroke-dashoffset: 1000;
-webkit-animation: dash 5s ease-in forwards;
-moz-animation:dash 5s ease-in forwards;
-o-animation:dash 5s ease-in forwards;
animation:dash 5s ease-in forwards;
}
#keyframes dash {
to { stroke-dashoffset: 0; }
}
function path(δr_min,δr_max, el0_min, el0_max, δel_min,δel_max) {
var c = 0.551915024494;
var atan = Math.atan(c)
var d = Math.sqrt( c * c + 1 * 1 ), r = 1;
var el = (el0_min + Math.random() * (el0_max - el0_min)) * Math.PI / 180;
var path = 'M';
path += [r * Math.sin(el), r * Math.cos(el)];
path += ' C' + [d * r * Math.sin(el + atan), d * r * Math.cos(el + atan)];
for (var i = 0; i < 4; i++) {
el += Math.PI / 2 * (1 + δel_min + Math.random() * (δel_max - δel_min));
r *= (1 + δr_min + Math.random()*(δr_max - δr_min));
path += ' ' + (i?'S':'') + [d * r * Math.sin(el - atan), d * r * Math.cos(el - atan)];
path += ' ' + [r * Math.sin(el), r * Math.cos(el)];
}
return path;
}
function cX(λ_min, λ_max, el_min, el_max) {
var el = (el_min + Math.random()*(el_max - el_min));
return 'rotate(' + el + ') ' + 'scale(1, ' + (λ_min + Math.random()*(λ_max - λ_min)) + ')'+ 'rotate(' + (-el) + ')';
}
function canvasArea() {
var width = Math.floor((Math.random() * 500) + 450);
var height = Math.floor((Math.random() * 300) + 250);
$('#container').width(width).height(height);
}
d3.selectAll( 'svg' ).append( 'path' ).classed( 'ln', true) .attr( 'd', path(-0.1,0, 0,360, 0,0.2 )).attr( 'transform', cX( 0.6, 0.8, 0, 360 ));
setTimeout(function() { location = '' } ,5000)

Draw arc with increasing radius?

I am drawing an arc which increases gradually and turns in to a circle.On completion of animation(arc turning in to a circle) i want to draw another circle with increased radius with the previous circle persisting and the second animation continuing.
Arc to circle fiddle
After the circle is drawn,it gets washed out which is something that I dont want and continue the second animation.
Some unnecessary animation appears after the completion.
What should I do?
MyCode:
setInterval(function(){
context.save();
context.clearRect(0,0,500,400);
context.beginPath();
increase_end_angle=increase_end_angle+11/500;
dynamic_end_angle=end_angle+increase_end_angle;
context.arc(x,y,radius,start_angle,dynamic_end_angle,false);
context.lineWidth=6;
context.lineCap = "round";
context.stroke();
context.restore();
if(dynamic_end_angle>3.5*Math.PI){ //condition for if circle completion
draw(radius+10);//draw from same origin and increasd radius
}
},66);
window.onload=draw(30);
UPDATE:when should i clear the interval to save some cpu cycles and why does the animation slows down on third circle ??
First of all, about the flicker: you are using setInterval and not clearing it for the next draw(). So there’s that.
But I’d use a completely different approach; just check the time elapsed since the start, and draw an appropriate number of circles using a loop.
var start = new Date().getTime();
var timePerCircle = 2;
var x = 190, y = 140;
function draw() {
requestAnimationFrame(draw);
g.clearRect(0, 0, canvas.width, canvas.height);
var t = (new Date().getTime() - start) / 1000;
var circles = t / timePerCircle;
var r = 30;
do {
g.beginPath();
g.arc(x, y, r, 0, Math.PI * 2 * Math.min(circles, 1));
g.stroke();
r += 10;
circles--;
} while(circles > 0);
}
draw();
This snippet from your code has some flaw.
if(dynamic_end_angle>3.5*Math.PI){ //condition for if circle completion
draw(radius+10);//draw from same origin and increased radius
}
The recursive call to draw() will continue to run after the first circle was drawn completely. This is why the performance will be slow down immediately. You need to somehow block it.
I did a simple fix, you can polish it if you like. FIDDLE DEMO
My fix is to remove context.clearRect(0, 0, 500, 400); and change the new circle drawing logic to:
if (dynamic_end_angle > 3.5 * Math.PI) { //condition for if circle completion
increase_end_angle = 0; // this will prevent the draw() from triggering multiple times.
draw(radius + 10); //draw from same origin.
}
In this stackoverflow thread, it mentions how to make it more smooth. You'd better use some drawing framework since the optimization needs a lot of work.
When should I clear the interval to save some cpu cycles?
Better yet not use an interval at all for a couple of reasons:
Intervals are unable to sync to monitor's VBLANK gap so you will get jerks from time to time.
If you use setInterval you risk stacking calls (not high risk in this case though).
A much better approach is as you probably already know to use requestAnimationFrame. It's less CPU hungry, is able to sync to monitor and uses less resources in general even less if current tab/window is not active.
Why does the animation slows down on third circle ??
Your drawing calls are accumulating which slows everything down (setInterval is not cleared).
Here is a different approach to this. It's a simplified way and uses differential painting.
ONLINE DEMO
The main draw function here takes two arguments, circle index and current angle for that circle. The circles radius are stored in an array:
...,
sa = 0, // start angle
ea = 359, // end angle
angle = sa, // current angle
oldAngle = sa, // old angle
steps = 2, // number of degrees per step
current = 0, // current circle index
circles = [70, 80, 90], // the circle radius
numOfCircles = circles.length, ...
The function stores the old angle and only draws a new segment between old angle and new angle with 0.5 added to compensate for glitches due to anti-alias, rounding errors etc.
function drawCircle(circle, angle) {
angle *= deg2rad; // here: convert to radians
/// draw arc from old angle to new angle
ctx.beginPath();
ctx.arc(0, 0, circles[circle], oldAngle, angle + 0.5);
ctx.stroke();
/// store angle as old angle for next round
oldAngle = angle;
}
The loop increases the angle, if above or equal to end angle it will reset the angle and increase the current circle counter. When current counter has reach last circle the loop ends:
function loop() {
angle += steps;
/// check angle and reset, move to next circle
if (angle >= ea - steps) {
current++;
angle = sa;
oldAngle = angle;
}
drawCircle(current, angle);
if (current < numOfCircles)
requestAnimationFrame(loop);
}

Categories