Animate a Fill Circle like pie chart using Canvas - javascript

Basically I want to be able to Fill a Circle using canvas, but it animate like pie chart and mask to show new image in circle.
My canvas knowledge isn't amazing, Here is an image to display what i want.
an anyone shed some light on how to do it?
Here is a fiddle of what I've managed
var canvas = document.getElementById('Circle');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 80;
var full = radius*2;
var amount = 0;
var amountToIncrease = 0.1;
function draw() {
context.beginPath();
context.arc(centerX, centerY, radius, 0, amount * Math.PI, false);
context.fillStyle = '#13a8a4';
context.fill();
context.lineWidth = 10;
context.strokeStyle = '#000000';
context.stroke();
amount += amountToIncrease;
if (amount > full) amount = 0; // restart
}
draw();
// Every second we'll fill more;
setInterval(draw, 100);

This is one way:
Draw your gray background.
Fill your percent-arc with a starting angle at -Math.PI*2 (=="12 on a clock") and an ending angle of -Math.PI*2 + Math.PI*2*percent (==a full circle of 2PI times your desired percent).
Draw your logo.
To animate, just use a requestAnimationFrame loop that incrementally draws the percent-arc starting at 0 percent and ending at your target percent.
Example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var nextTime=0;
var duration=1000;
var endingPct=75;
var pct=0;
var increment=duration/pct;
requestAnimationFrame(animate);
function animate(time){
draw(pct);
pct++;
if(pct<=endingPct){requestAnimationFrame(animate);}
}
function draw(pct){
var endRadians=-Math.PI/2+Math.PI*2*pct/100;
ctx.fillStyle='lightgray';
ctx.fillRect(0,0,cw,ch);
ctx.beginPath();
ctx.arc(150,125,100,-Math.PI/2,endRadians);
ctx.lineTo(150,125);
ctx.fillStyle='white';
ctx.fill();
ctx.beginPath();
ctx.moveTo(150,100);
ctx.lineTo(175,150);
ctx.quadraticCurveTo(150,125,125,150);
ctx.closePath();
ctx.strokeStyle='#13a8a4';
ctx.lineJoin='bevel';
ctx.lineWidth=10;
ctx.stroke();
ctx.fillStyle='black';
ctx.textAlign='center';
ctx.textBaseline='middle'
ctx.font='18px arial';
ctx.fillText('ADUR',150,175);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>
[Update: We needed an image clipped inside the animated wedge]
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var nextTime=0;
var duration=1000;
var endingPct=75;
var pct=0;
var increment=duration/pct;
var cx=cw/2;
var cy=ch/2;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/mm.jpg";
function start(){
requestAnimationFrame(animate);
}
function animate(time){
draw(pct);
pct++;
if(pct<=endingPct){requestAnimationFrame(animate);}
}
function draw(pct){
//
var endRadians=-Math.PI/2+Math.PI*2*pct/100;
//
ctx.fillStyle='lightgray';
ctx.fillRect(0,0,cw,ch);
//
ctx.beginPath();
ctx.arc(cx,cy,100,-Math.PI/2,endRadians);
ctx.lineTo(cx,cy);
ctx.save();
ctx.clip();
ctx.drawImage(img,cx-img.width/2,cx-img.height/2);
ctx.restore();
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

Related

Javascript animation of arc() length

I know that this question may have already been answered, but I am having a hard time figuring out how to do it with my code.
What I would like is for the arc of the circle to do a draw animation from 0deg to 360deg whenever the mouse is clicked.
I know that I should put this in a loop that increases the angle, but I keep running into issues with (I think) translate.
Here is my code so far:
https://jsfiddle.net/s7aufv0g/2/
This is where I draw the ball:
// Draw the ball
ctx.clearRect(0,0,width,height);
ctx.save();
ctx.translate(ball.position.x, ball.position.y);
ctx.beginPath();
ctx.arc(0, 0, ball.radius, 0, Math.PI*2, true);
ctx.stroke();
ctx.closePath();
ctx.restore();
Any help would be great, thank you very much.
Don't bother with context.translate because you can set the arc's centerX & centerY directly in the context.arc command.
You can control how much of the 360 degree arc angle is shown in the animation by setting the startAngle & endAngle in context.arc(centerX,centerY,radius,startAngle,endAngle).
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var cx=cw/2;
var cy=ch/2;
var radius=Math.min(cw,ch)*.75/2;
var startAngle=-Math.PI/2;
var accumAngle=0;
var increment=Math.PI*2/120;
ctx.lineWidth=13;
ctx.strokeStyle='skyblue';
requestAnimationFrame(animate);
$("#canvas").mousedown(function(e){handleMouseDown(e);});
function handleMouseDown(e){
if(accumAngle>=Math.PI*2){
accumAngle=0;
requestAnimationFrame(animate);
}
}
function animate(time){
accumAngle+=increment;
ctx.clearRect(0,0,cw,ch);
ctx.beginPath();
ctx.arc(cx,cy,radius,startAngle,startAngle+accumAngle);
ctx.stroke();
if(accumAngle<=Math.PI*2){ requestAnimationFrame(animate); }
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Click in red canvas to begin arc animation<br>You must wait for any current circle to finish drawing.</h4>
<canvas id="canvas" width=300 height=300></canvas>
Here is someone else's fiddle animating the drawing of arc(). Perhaps it will get you pointed in the right direction. Add a click handler to start the draw() method and you should be good to go.
HTML
<html>
<head>
</head>
<body>
<canvas id="canvas1" width="500" height="500"></canvas>
</body>
</html>
JS
var currentEndAngle = 0
var currentStartAngle = 0;
var currentColor = 'black';
var lineRadius = 75;
var lineWidth = 15;
setInterval(draw, 50);
function draw() { /***************/
var can = document.getElementById('canvas1'); // GET LE CANVAS
var canvas = document.getElementById("canvas1");
var context = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius;
var width;
var startAngle = currentStartAngle * Math.PI;
var endAngle = (currentEndAngle) * Math.PI;
currentStartAngle = currentEndAngle - 0.01;
currentEndAngle = currentEndAngle + 0.01;
if (Math.floor(currentStartAngle / 2) % 2) {
currentColor = "white";
radius = lineRadius - 1;
width = lineWidth + 3;
} else {
currentColor = "black";
radius = lineRadius;
width = lineWidth;
}
var counterClockwise = false;
context.beginPath();
context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
context.lineWidth = width;
context.lineCap = "round";
// line color
context.strokeStyle = currentColor;
context.stroke();
http://jsfiddle.net/umaar/fnMvf/

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();
}

How to draw and rotate image along with text in HTML5 canvas

I am having a problem with drawing and rotating image on my canvas. Basically, my approach is to create the wheel of fortune which allows customization based on the prizes in form of array. The data in this array makes up the segment inside the wheel based on the number of indexes.
The data is very simple. It is just a simple JSON object like this
var prizes = [
{product:"Axe FX", img: "https://mdn.mozillademos.org/files/5395/backdrop.png"},
{product:"Musicman JPX", img: "https://mdn.mozillademos.org/files/5395/backdrop.png"},
{product:"Ibanez JEM777V", img: "https://mdn.mozillademos.org/files/5395/backdrop.png"}
];
This data is used to create the segments inside the wheel. So I want to place the text which is currently working like a charm for me.
When drawing the wheel, I separate into two main functions. One to draw the wheel and another to draw the segments inside the wheel.
var drawPartial = function(key, lastAngle, angle) {
var value = prizes[key].product;
ctx.save();
ctx.beginPath();
ctx.lineWidth = 6;
ctx.fillStyle = segColors[key];
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, size, lastAngle, angle);
ctx.lineTo(centerX, centerY);
ctx.closePath();
ctx.stroke();
ctx.fill();
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate((lastAngle+angle) / 2);
ctx.fillStyle = "#000";
ctx.fillText(value.substr(0,20), size / 2 + 20, 0);
ctx.restore();
ctx.restore();
}
var draw = function() {
var len = prizes.length;
var currentAngle = outCurrentAngle;
var lastAngle = currentAngle;
ctx.strokeStyle = '#000000';
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.font = "1.4em Arial";
for(var i = 1; i <= len; i++) {
var angle = (Math.PI*2) * (i/len) + currentAngle;
drawPartial(i-1, lastAngle, angle);
lastAngle = angle;
}
ctx.beginPath();
ctx.lineWidth = 2;
ctx.fillStyle = "#fff";
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, size/7, 0, Math.PI*2);
ctx.closePath();
// ctx.stroke();
ctx.fill();
ctx.beginPath();
ctx.lineWidth = 10;
ctx.arc(centerX, centerY, size, 0, Math.PI*2);
ctx.closePath();
// ctx.stroke();
}
With the code above, I just simple call the draw() function and the wheel and all segments will be created accordingly. However, I want to draw the image in each segment but I don't know to make it work. This is the modification of drawPartial() for rendering images along with text
var drawPartial = function(key, lastAngle, angle) {
var value = prizes[key].product;
var img = new Image();
img.src = prizes[key].img;
img.onload = function() {
ctx.save();
ctx.drawImage(img,centerX,centerY);
ctx.save();
ctx.translate(centerX,centerY);
ctx.rotate((lastAngle+angle) / 2);
ctx.drawImage(img,centerX,centerY);
ctx.restore();
ctx.restore();
}
ctx.save();
ctx.beginPath();
ctx.lineWidth = 6;
ctx.fillStyle = segColors[key];
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, size, lastAngle, angle);
ctx.lineTo(centerX, centerY);
ctx.closePath();
ctx.stroke();
ctx.fill();
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate((lastAngle+angle) / 2);
ctx.fillStyle = "#000";
ctx.fillText(value.substr(0,20), size / 2 + 20, 0);
ctx.restore();
ctx.restore();
}
You can see that I add image and its src based on the prizes object which should be called in each iteration called by the main draw() function but it never renders any image in any segment.
What I want is. In each iteration of drawPartial(), I want the image to be placed in the segment along with the text and rotated according to the angle.
Please help...
Problem
In your img.onload function you are "double translating" your centerX & centerY.
ctx.translate(centerX,centerY) will move the canvas's [0,0] origin to [centerX,centerY].
So when you ctx.drawImage(img,centerX,centerY) to draw your image, you are really double moving.
As a result your image is really being drawn at [ centerX*2, centerY*2 ].
A additional thought: Preload your images
It's best to preload all your images. That way if an image fails to load you can take reparative action before you begin drawing your wheel.
Here is how to preload all of your images so they are available when you need to draw them onto your Wheel:
// your incoming JSON
var prizesJSON='[{"product":"Axe FX","img":"https://mdn.mozillademos.org/files/5395/backdrop.png"},{"product":"Musicman JPX","img":"https://mdn.mozillademos.org/files/5395/backdrop.png"},{"product":"Ibanez JEM777V","img":"https://mdn.mozillademos.org/files/5395/backdrop.png"}]';
// the JSON converted to a JS array of objects
var prizes=JSON.parse(prizesJSON);
// preload all images
var imageURLs=[];
var imgs=[];
var imagesOK=0;
// add prize images into the image preloader
for(var i=0;i<prizes.length;i++){
imageURLs.push(prizes[i].img);
}
startLoadingAllImages(imagesAreNowLoaded);
//
function startLoadingAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.src = imageURLs[i];
}
}
//
function imagesAreNowLoaded(){
// add the img objects to your prizes array objects
for(var i=0;i<prizes.length;i++){
prizes[i].imageObject=imgs[i];
// just testing (add the img to the DOM)
document.body.appendChild(imgs[i]);
}
// All images are fully loaded
// So draw your wheel now!
}
body{ background-color: ivory; }
<h4>Testing: (1) Preload all images, (2) Add imgs to DOM</h4>
I had this laying around...
I see you already have code to draw your Wheel, but I had this code in my code archive so I offer it here just in case it has some use for you.
Here is an example of how to draw a "Wheel of Fortune" with each blade containing a prize image and text. The techniques used include:
context.translate to set the rotation point to the center of the wheel.
context.rotate to rotate each blade to its desired angle.
context.textAlign & context.textBaseline to draw centered text.
context.globalAlpha to lighten each blades color so the black text has good contrast.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var PI=Math.PI;
var PI2=PI*2;
var bladeCount=10;
var sweep=PI2/bladeCount;
var cx=cw/2;
var cy=ch/2;
var radius=130;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house32x32transparent.png";
function start(){
for(var i=0;i<bladeCount;i++){
drawBlade(img,'House'+i,cx,cy,radius,sweep*i,sweep);
}
}
function drawBlade(img,text,cx,cy,radius,angle,arcsweep){
// save the context state
ctx.save();
// rotate the canvas to this blade's angle
ctx.translate(cx,cy);
ctx.rotate(angle);
// draw the blade wedge
ctx.lineWidth=1.5;
ctx.beginPath();
ctx.moveTo(0,0);
ctx.arc(0,0,radius,0,arcsweep);
ctx.closePath();
ctx.stroke();
// fill the blade, but keep the color light
// so the black text has good contrast
ctx.fillStyle='white';
ctx.fill();
ctx.fillStyle=randomColor();
ctx.globalAlpha=0.30;
ctx.fill();
ctx.globalAlpha=1.00;
// draw the text
ctx.rotate(PI/2+sweep/2);
ctx.textAlign='center';
ctx.textBaseline='middle';
ctx.fillStyle='black';
ctx.fillText(text,0,-radius+50);
// draw the img
// (resize to 32x32 so be sure orig img is square)
ctx.drawImage(img,-16,-radius+10,32,32);
// restore the context to its original state
ctx.restore();
}
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

How would I align circles horizontally using loops?

I have managed to get the circles on top of each other but I have no clue how to make a line of circles that do not overlap.
This is what I have gotten so far.
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script src="js/main.js"></script>
</body>
</html>
JavaScript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
for(var i = 0; i < 10; i++) {
ctx.fillStyle="rgba(0,0,0,0.5)";
fillCircle(200,200,i*20)
}
var width = window.innerWidth;
var height = 100;
function fillCircle(x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
The x-value of any next circle must be at least be the sum of the current and next circle radii beyond the current circle's x-value.
So if:
var currentCircleX=20
var currentCircleRadius=15
var nextCircleRadius=25
Then:
var nextCircleX = currentCircleX + currentCircleRadius + nextCircleRadius
But if you are also stroking the circles:
Since a context stroke will extend half-outside the defined path, you must also add half the lineWidth for each circle to avoid the circles touching:
// account for the lineWidth that extends beyond the arc's path
var nextCircleX =
currentCircleX + currentCircleRadius + nextCircleRadius + context.lineWidth
Example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.fillStyle="rgba(0,0,0,0.5)";
var currentCircleX=0;
var currentCircleRadius=0;
for(var i = 0; i < 10; i++) {
var nextCircleRadius=i*20;
var nextCircleX=currentCircleX+currentCircleRadius+nextCircleRadius;
fillCircle(nextCircleX,200,nextCircleRadius);
currentCircleX=nextCircleX;
currentCircleRadius=nextCircleRadius;
}
function fillCircle(x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

Paint circle method JavaScript

I am trying to find a way to draw a circle using JavaScript and redraw it while erasing the old circle.
i got this code:
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 15;
drawCircle(centerX,centerY,radius);
drawCircle(150,150,25);
function drawCircle(centerX,centerY,radius)
{
var canvas = document.getElementById('myCanvas');
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'black';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
};
</script>
The problem is that this two methods draw two circles instead of drawing one instead of the other.
I am beginner in JS would appreciate help on making better way of drawing and erasing the circle
Thanks
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 15;
function drawCircle(centerX,centerY,radius)
{
// Erase context
context.clearRect(0,0,canvas.width,canvas.height);
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'black';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
};
drawCircle(centerX,centerY,radius);
drawCircle(150,150,25);
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
If you want to remove a circle from the canvas you will have to draw a circle (same position; same size) but this time with the color of the canvas background.
drawCircle(150,150,25,'black');
// ...
drawCircle(150,150,25,'white'); // removes previous circle if the canvas was white colored
If you want to erase everything from the canvas before drawing something new you can just execute this
context.clearRect(0, 0, canvas.width, canvas.height);

Categories

Resources