How to use RequestAnimationFrame correctly? - javascript

I made a diffuse animation and used RequestAnimationFrame to achieve it.I tried hundreds of times to improve my program.But it doesn't work!!!Where's my wrong?
function draw_point(x, y){
x += 10.5;
y += 10.5;
radius = 0;
var context = $("#canvas_graph")[0].getContext('2d');
window.webkitRequestAnimationFrame(render(x, y, radius, context));
};
function drawCircle(x, y, radius, context){
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2);
context.closePath();
context.lineWidth = 2;
context.strokeStyle = 'red';
context.stroke();
radius += 0.2;
if (radius > 10) {
radius = 0;
}
};
//The effect of diffusion is achieved by changing the attribute
function render(x ,y, radius, context){
return function step(){
var prev = context.globalCompositeOperation;
context.globalCompositeOperation = 'destination-in';
context.globalAlpha = 0.95;
context.fillRect(0, 0, 890, 890);
context.globalCompositeOperation = prev;
drawCircle(x, y, radius,context);
window.webkitRequestAnimationFrame(step);
};
};
draw_point(100, 100);
But this can be used normally.Function render through the globalAlpha attribute so that the circle is getting lighter.Newly drawn circles are getting bigger.Small rounds are becoming lighter and lighter by using the globalAlpha property again and again.
var context = $("#canvas_graph")[0].getContext('2d');
var radius = 0;
var x = 100;
var y = 100;
function drawCircle(){
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2);
context.closePath();
context.lineWidth = 2;
context.strokeStyle = 'red';
context.stroke();
radius += 0.2;
if (radius > 10) {
radius = 0;
}
};
function render(){
var prev = context.globalCompositeOperation;
context.globalCompositeOperation = 'destination-in';
context.globalAlpha = 0.95;
context.fillRect(0, 0, 890, 890);
context.globalCompositeOperation = prev;
drawCircle();
window.webkitRequestAnimationFrame(render);
};
window.webkitRequestAnimationFrame(render);
In addition,when canvas animation move up, how to restore the background?

Adjust your draw_point function like so. What you have currently is executing the render function right away, you want to pass a reference to requestAnimationFrame, not inserting a function call there
function draw_point(x, y){
x += 10.5;
y += 10.5;
radius = 0;
var context = $("#canvas_graph")[0].getContext('2d');
window.webkitRequestAnimationFrame(function() {
render(x, y, radius, context));
}
};

Related

Rotate a triangle in the cente of itself

I want to rotate a triangle in the center of itself.
I have this script:
var ctx = canvas.getContext('2d');
var angle = 30;
setInterval(rotate, 50);
function rotate() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(150, 150); // x, y
ctx.rotate(angle * Math.PI / 180)
ctx.fillStyle = "yellow";
var path=new Path2D();
path.moveTo(-50+50,-25);
path.lineTo(-50,-50-25);
path.lineTo(-50-50,-25);
ctx.fill(path);
ctx.restore();
angle++;
}
<canvas id="canvas" width="1800" height="700"></canvas>
It rotates it, but not in the center. I want it to look like this:
var ctx = canvas.getContext('2d');
setInterval(rotate, 50);
var angle = 30;
function rotate() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(50, 50);
ctx.rotate(angle * Math.PI / 180)
ctx.fillStyle = "green";
ctx.fillRect(-25, -25, 50, 50);
ctx.restore();
angle++;
}
<canvas id="canvas" width="1800" height="700"></canvas>
I think, I just have to get the width and hight of the triangle and devive it by 2, but I don't know, how to do that.
Thx for every answer!
What you want is the centroid of your shape.
var ctx = canvas.getContext('2d');
var angle = 30;
var points = [
{x:0, y:-25},
{x:-50, y:-75},
{x:-100, y:-25}
];
// first sum it all
var sums = points.reduce( (sum, point) => {
sum.x += point.x;
sum.y += point.y;
return sum;
}, {x:0, y:0});
// we want the mean
var centroid = {
x: sums.x / points.length,
y: sums.y / points.length
};
rotate();
function rotate() {
ctx.setTransform(1,0,0,1,0,0);
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// general position in canvas
ctx.translate(100, 100);
// move to centroid of our triangle
ctx.translate(centroid.x, centroid.y); // x, y
// rotate
ctx.rotate(angle * Math.PI / 180)
// go back to our initial position
ctx.translate(-centroid.x, -centroid.y); // x, y
ctx.fillStyle = "yellow";
var path=new Path2D();
path.moveTo(points[0].x, points[0].y);
path.lineTo(points[1].x, points[1].y);
path.lineTo(points[2].x, points[2].y);
ctx.fill(path);
// demo only
ctx.beginPath();
ctx.arc(centroid.x, centroid.y, 50, 0, Math.PI*2)
ctx.stroke();
angle++;
requestAnimationFrame( rotate );
}
<canvas id="canvas" width="1800" height="700"></canvas>
Create the Path once
You are using a Path2D object which is reusable.
If you create the triangle already centered on its origin (or any path for that matter) it is then trivial to rotate it.
Reusing the path object is also a lot quicker if you have a lot to render.
The function to creates a path from a set of points. It automatically centers the path to its own origin (defined by the mean of its points)
const point = (x, y) => ({x, y});
function createPath(...points) {
var cx = 0; cy = 0;
for (const p of points) {
cx += p.x;
cy += p.y;
}
cx /= points.length;
cy /= points.length;
const path = new Path2d;
for (const p of points) { path.lineTo(p.x - cx, p.y - cy); }
path.closePath();
return path;
}
To create the triangle
const triangle = createPath(point(0,-25), point(-50,-75), point(-100,-25));
Then you can render it rotated about its own origin with
function drawPath(path, x, y, angle) {
ctx.setTransform(1, 0, 0, 1, x, y);
ctx.rotate(angle);
ctx.stroke(path);
}
Example
Shows how to create various shapes centered on their means. Each shape is a path created once and then rendered as needed.
const point = (x, y) => ({x, y});
const triangle = createPath(point(0,-25), point(-50,-75), point(-100,-25));
const rectangle = createPath(point(0,-25), point(-50,-25), point(-50,-125), point(0,-125));
const thing = createPath(point(0,-12), point(-25,-12), point(-25,-62), point(0,-62), point(22,-35));
function drawPath(path, x, y, angle) {
ctx.setTransform(1, 0, 0, 1, x, y);
ctx.rotate(angle);
ctx.stroke(path);
}
function drawPath_V2(path, x, y, scale, angle, strokeStyle, fillStyle) {
ctx.setTransform(scale, 0, 0, scale, x, y);
ctx.rotate(angle);
fillStyle && (ctx.fillStyle = fillStyle, ctx.fill(path));
strokeStyle && (ctx.strokeStyle = strokeStyle, ctx.stroke(path));
}
function renderLoop(time) {
ctx.clearRect(0, 0, can.width, can.height);
const scale = Math.sin(time / 500) * 0.2 + 1.0;
const scale2 = Math.cos(time / 1000) * 0.4 + 1.0;
drawPath(triangle, 75, 74, time / 1000 * Math.PI); //360 every 2 second
// scale path
drawPath_V2(rectangle, 125, 125, scale, time / 2000 * Math.PI, "black"); //360 every 4 second
// fill scale path
drawPath_V2(thing, 125, 100, scale2, time / 3000 * Math.PI, "", "black");
ctx.setTransform(1, 0, 0, 1, 0, 0);
requestAnimationFrame(renderLoop);
}
requestAnimationFrame(renderLoop);
const can = Object.assign(document.createElement("canvas"), {width: 200, height: 200});
document.body.appendChild(can);
const ctx = can.getContext("2d");
function createPath(...points) {
var cx = 0; cy = 0;
for (const p of points) {
cx += p.x;
cy += p.y;
}
cx /= points.length;
cy /= points.length;
const path = new Path2D;
for (const p of points) {
path.lineTo(p.x - cx , p.y - cy);
}
path.closePath();
return path;
}

Javascript canvas animated arc

I've been learning some javascript/canvas animation, I'm having trouble getting this animation to work correctly.
My goal is that the animation will start drawing at the top, then as it gets back to the top it will stop progressing and the start position will progress around the arc making it look as though it is erasing itself and once at the top (1.5 * PI) will starting drawing again.
Here is a fiddle: https://jsfiddle.net/kg1fmsjj/
Here is my code:
function f(element, colour, thickness, elapsedTime) {
// Create Element
element.innerHTML = '';
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
element.appendChild(canvas);
// Circle Params
context.lineWidth = thickness;
context.strokeStyle = colour;
var width = canvas.width;
var height = canvas.height;
var mathPi = Math.PI;
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 40;
var startAngle = 1.5 * mathPi;
var endAngle = 1.5 * mathPi;
context.lineWidth = thickness;
context.strokeStyle = colour;
var erasing = false;
function animate() {
if(erasing) {
startAngle = startAngle + 0.01 * mathPi;
} else {
endAngle = endAngle + 0.01 * mathPi;
}
if (endAngle > (1.5 * mathPi)) {
erasing = true;
}
if (startAngle > (1.5 * mathPi)) {
erasing = false;
}
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, false);
context.stroke();
context.closePath();
}
setInterval(animate, 10);
}
f(document.getElementById('out'), '#800080', 4, 60);
context.arc lets you optionally draw your arc counterclockwise.
This ability lets you create your desired effect:
To "draw" the arc, draw an increasing arc clockwise.
To "erase" the arc, draw a decreasing arc counterclockwise.
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;
ctx.lineWidth=2;
ctx.strokeStyle='#800080';
var PI=Math.PI;
var cx=cw/2;
var cy=ch/2;
var radius=cw/2-30;
var angle=0;
var direction=1;
requestAnimationFrame(animate);
function animate(time){
ctx.clearRect(0,0,cw,ch);
angle+=PI/120;
if(angle<0 || angle>PI*2){
angle=0;
direction*=-1;
}
draw();
requestAnimationFrame(animate);
}
function draw(){
var counterclockwise=(direction>0)?false:true;
var s=-Math.PI/2;
var e=angle-Math.PI/2;
ctx.beginPath();
ctx.arc(cx,cy,radius,s,e,counterclockwise);
ctx.stroke();
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>
You need to clear the canvas on each repaint using the clearRect() method.
You need to change the conditions when erasing variable is toggled. If erasing and startAngle >= endAngle then toggle erasing variable. If not erasing and endAngle >= startAngle + 2 * PI then toggle erasing variable.
The animate() method then become...
function animate() {
if(erasing) {
startAngle = startAngle + 0.01 * mathPi;
if (startAngle >= endAngle) {
erasing = false;
}
} else {
endAngle = endAngle + 0.01 * mathPi;
if (endAngle >= startAngle + 2.0 * mathPi) {
erasing = true;
}
}
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, false);
context.stroke();
}

'loading circle' through Canvas

Alright guys, I'm sure this has been asked before, but I couldn't find anything that directly related to what I was doing. So I have these 4 self drawing circles (or gauges.) Each one has it's own value, and I've been looking through just nit picking through codes and books to build this. My question I need to figure out is how I would go about putting in a count up? Basically I want a counter to go from 1 - x (x being the degree of the circle it's in). I've included my js and HTML 5 for you guys to look at.
HTML
<canvas id="a" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById('a');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var startAngle = 1.5 * Math.PI;
var endAngle = 3.2 * Math.PI;
var counterClockwise = false;
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.lineWidth = 15;
// line color
context.strokeStyle = 'black';
context.stroke();
</script>
Canvas.JS
$(document).ready(function(){
function animate(elementId, endPercent) {
var canvas = document.getElementById(elementId);
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var curPerc = 0;
var counterClockwise = false;
var circ = Math.PI * 2;
var quart = Math.PI / 2;
context.lineWidth = 15;
context.strokeStyle = '#85c3b8';
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 10;
function render(current) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(x, y, radius, -(quart), ((circ) * current) - quart, false);
context.stroke();
curPerc++;
if (curPerc < endPercent) {
requestAnimationFrame(function () {
render(curPerc / 100);
});
}
}
render();
}
$(window).scroll(function(){
if($(this).scrollTop()<1600){
animate('a', 85);
animate('b', 95);
animate('c', 80);
animate('d', 75);
}
});
});
Keep in mind that I am very new to canvas, I appreciate all the help guys!
Demo: http://jsfiddle.net/m1erickson/mYKp5/
You can save your gauges as objects in an array:
var guages=[];
guages.push({ x:50, y:100, radius:40, start:0, end:70, color:"blue" });
guages.push({ x:200, y:100, radius:40, start:0, end:90, color:"green" });
guages.push({ x:50, y:225, radius:40, start:0, end:35, color:"gold" });
guages.push({ x:200, y:225, radius:40, start:0, end:55, color:"purple" });
The render function takes a guage object draws its progress
function render(guage,percent) {
var pct=percent/100;
var extent=parseInt((guage.end-guage.start)*pct);
var current=(guage.end-guage.start)/100*PI2*pct-quart;
ctx.beginPath();
ctx.arc(guage.x,guage.y,guage.radius,-quart,current);
ctx.strokeStyle=guage.color;
ctx.stroke();
ctx.fillStyle=guage.color;
ctx.fillText(extent,guage.x-15,guage.y+5);
}
And the animation loop asks render to draw all gauges from 0-100 percent of their full values
function animate() {
// if the animation is not 100% then request another frame
if(percent<100){
requestAnimationFrame(animate);
}
// redraw all guages with the current percent
drawAll(percent);
// increase percent for the next frame
percent+=1;
}
function drawAll(percent){
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw all the guages
for(var i=0;i<guages.length;i++){
render(guages[i],percent);
}
}

Animation loop and scaling

Well I've got a few question to ask! Firstly What this code is doing is creating and drawing snowflakes with unique density which will all fall at a different rate. My first question is how do i make this loop continuous?
Secondly, I've translated my origin point(0,0) to the middle of the canvas (it was part of the criteria). I've now got this issue in which that when the snowfall is called it will either be drawn on the left side of the screen or the right, not both. How do i solve this?
Finally i know when doing animations that you have to clear the canvas after each re-drawing, however i haven't added this in and yet it still works fine?
//Check to see if the browser supports
//the addEventListener function
if(window.addEventListener)
{
window.addEventListener
(
'load', //this is the load event
onLoad, //this is the evemnt handler we going to write
false //useCapture boolen value
);
}
//the window load event handler
function onLoad(Xi, Yy) {
var canvas, context,treeObj, H, W, mp;
Xi = 0;
Yy = 0;
mp = 100;
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
W = window.innerWidth;
H = window.innerHeight;
canvas.width = W;
canvas.height = H;
context.translate(W/2, H/2);
var particles = [];
for(var i = 0; i < mp; i++) {
particles.push({
x: Math.random()*-W, //x
y: Math.random()*-H, //y
r: Math.random()*6+2, //radius
d: Math.random()* mp // density
})
}
treeObj = new Array();
var tree = new TTree(Xi, Yy);
treeObj.push(tree);
function drawCenterPot(){
context.beginPath();
context.lineWidth = "1";
context.strokeStyle = "Red";
context.moveTo(0,0);
context.lineTo(0,-H);
context.lineTo(0, H);
context.lineTo(-W, 0);
context.lineTo(W,0);
context.stroke();
context.closePath();
}
function drawMountain() {
context.beginPath();
context.fillStyle = "#FFFAF0";
context.lineWidth = "10";
context.strokeStyle = "Black";
context.moveTo(H,W);
context.bezierCurveTo(-H*10,W,H,W,H,W);
context.stroke();
context.fill();
}
function drawSky() {
var linearGrad = context.createLinearGradient(-100,-300, W/2,H);
linearGrad.addColorStop(0, "#000000");
linearGrad.addColorStop(1, "#004CB3");
context.beginPath();
context.fillStyle = linearGrad;
context.fillRect(-W/2, -H/2, W, H);
context.stroke();
context.fill();
drawMountain();
drawCenterPot();
}
function drawSnow(){
context.fillStyle = "White";
context.beginPath();
for(i = 0; i<mp; i++)
{
var p = particles[i];
context.moveTo(p.x,p.y);
context.arc(p.x, p.y, p.r, Math.PI*2, false);
}
context.fill();
}
function update() {
var angle = 0;
angle+=0.1;
for(var i=0; i<mp; i++) {
var p = particles[i];
p.x += Math.sin(angle) * 2;
p.y += Math.cos(angle+p.d) + 1 * p.r;
}
drawSky();
drawSnow();
draw();
}
function draw() {
for(var i =0; i < treeObj.length; i++)
{
context.save();
context.translate(Xi-H,Yy-W);
context.scale(1, 1);
treeObj[0].draw(context);
context.restore();
}
}
setInterval(update, 33);
}
About your animation:
What's happening is your flakes are falling out of view below the bottom of the canvas.
So when any flake's p.y+p.r > canvas.height you could:
destroy that flake and (optionally) add another falling from above the canvas
or
"recycle" that flake by changing its p.y to above the canvas.
About your design working without context.clearRect:
In your design, when you fill the whole canvas with "sky", you are effectively clearing the canvas.
About your flakes only falling on half the screen:
Instead of translating to mid-screen:
Don't translate at all and let p.x be any Math.random()*canvas.width

building a color wheel in html5

I am just learning some details about html5 canvas, and in the progress, I am trying to build a simple color wheel by wedges (build a 1 degree wedge at a time and add it up to 360 degree). However, I am getting some weird marks on the gradient as shown in the following image:
.
Here is the fiddle that produced the colorwheel: http://jsfiddle.net/53JBM/
In particular, this is the JS code:
var canvas = document.getElementById("picker");
var context = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 100;
var counterClockwise = false;
for(var angle=0; angle<=360; angle+=1){
var startAngle = (angle-1)*Math.PI/180;
var endAngle = angle * Math.PI/180;
context.beginPath();
context.moveTo(x, y);
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.closePath();
context.fillStyle = 'hsl('+angle+', 100%, 50%)';
context.fill();
}
If anyone can point out what I am doing wrong or if there is a better way to accomplish what I am attempting to do it would be much appreciated :)
Is this enough to you, please check
var startAngle = (angle-2)*Math.PI/180;
Try this it looks great.
Thanks by the way this is exactly what I was trying to make.
var canvas = document.getElementById("picker");
var context = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 100;
var counterClockwise = false;
for(var angle=0; angle<=360; angle+=1){
var startAngle = (angle-2)*Math.PI/180;
var endAngle = angle * Math.PI/180;
context.beginPath();
context.moveTo(x, y);
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.closePath();
var gradient = context.createRadialGradient(x, y, 0, x, y, radius);
gradient.addColorStop(0,'hsl('+angle+', 10%, 100%)');
gradient.addColorStop(1,'hsl('+angle+', 100%, 50%)');
context.fillStyle = gradient;
context.fill();
}
<body>
<canvas id="picker"></canvas>
</body>
Similar approach, just for the color
var canvas = document.getElementById("picker");
var context = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 50;
var thickness = 0.6;
for(var angle=0; angle<=360; angle+=1){
var startAngle = (angle-2)*Math.PI/180;
var endAngle = angle * Math.PI/180;
context.beginPath();
context.arc(x, y, (1-thickness/2)*radius, startAngle, endAngle, false);
context.lineWidth = thickness*radius;
context.strokeStyle = 'hsl('+angle+', 100%, 50%)';
context.stroke();
}
<body>
<canvas id="picker"></canvas>
</body>
Edit: full project here: https://github.com/dersimn/jquery-colorwheel

Categories

Resources