简体   繁体   中英

HTML5 spin circle

I am trying to spin a circle on a canvas, i think i got most of the code but i don't know whats wrong with the code, the circle is not spinning. Do i need to create another function in order to spin the circle? any suggestions

http://jsfiddle.net/qY85C/1/

var angle = 0;
function convertToRadians(degree) {
return degree*(Math.PI/180);
}

function incrementAngle() {
   angle++;
   if(angle > 360) {
    angle = 0;
   }
}

var myColor = ["#ECD078","#D95B43"];
var myData = [50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50];

function getTotal(){
var myTotal = 0;
for (var j = 0; j < myData.length; j++) {
    myTotal +=  myData[j];       
}
return myTotal;
}

function drawColoredCircle() {
var lastend = 0;
var myTotal = getTotal();//160

for (var i = 0; i < myData.length; i++) {
    ctxBg.fillStyle = myColor[i%2];
    ctxBg.translate(canvasBg.width/2, canvasBg.width/2);
    ctxBg.rotate(convertToRadians(angle));
    ctxBg.translate(-canvasBg.width/2, -canvasBg.width/2);
    ctxBg.beginPath();
    ctxBg.moveTo(canvasBg.width/2,canvasBg.width/2);
    ctxBg.arc(canvasBg.width/2,canvasBg.height/2,500,lastend,lastend+(Math.PI*2*(myData[i]/myTotal)),false);
    ctxBg.lineTo(canvasBg.width/2,canvasBg.height/2);
    ctxBg.fill();
    lastend += Math.PI*2*(myData[i]/myTotal);

}
}

function loop(){
    drawColoredCircle();
    requestAnimFrame(loop);
}

You need to change the angle inside your loop

function loop(){
    angle+=Math.PI/18000;
    drawColoredCircle();
    requestAnimFrame(loop);
}

Also, do you want to clear the canvas before drawing the circle?

function loop(){
    ctxBg.clearRect(0,0,canvasBg.width,canvasBg.height);
    angle+=Math.PI/18000;    
    drawColoredCircle();
    requestAnimFrame(loop);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM