http://jsfiddle.net/3RpvJ/5/
function Timer(dur, par, can, cnt) {
var parent = $(par),
canvas = can ? $(can, parent)[0] : $('.timer', parent)[0],
seconds = cnt ? $(cnt, parent)[0] : $('.counter', parent)[0],
//ctx = canvas.getContext('2d'),
sec = dur,
countdown = sec;
if (!canvas)
canvas = $("<canvas>").addClass('timer')
.attr('width', 100).attr('height', 100).appendTo(parent)[0];
if (!seconds)
seconds = $("<span>").addClass('counter').appendTo(parent)[0];
var ctx = canvas.getContext('2d');
ctx.lineWidth = 8;
ctx.strokeStyle = "#528f20";
var startAngle = 0,
time = 0,
intv = setInterval(function() {
var endAngle = (Math.PI * time * 2 / sec);
ctx.arc(65, 35, 30, startAngle, endAngle, false);
ctx.clearRect(0, 0, 200, 200);
startAngle = endAngle;
ctx.stroke();
countdown--;
if (countdown > 60) {
seconds.innerHTML = Math.floor(countdown / 60);
seconds.innerHTML += ":" + countdown % 60;
}
else {
seconds.innerHTML = countdown;
}
if (++time > sec, countdown == 0) {
clearInterval(intv);
$(canvas).remove();
$(seconds).remove();
$(par).prepend('<img id="theImg" src="http://ivojonkers.com/votify/upvote.png" />');
}
}, 10);
}
$(function() {
Timer(180, '#timer1');
Timer(240, '#timer2');
Timer(300, '#timer3');
Timer(360, '#timer4');
});
html:
<div id="timers">
<div id="timer1" class="time">
</div>
<div id="timer2" class="time">
</div>
<div id="timer3" class="time">
</div>
<div id="timer4" class="time">
</div>
</div>
CSS:
#timers canvas {
-webkit-transform : rotate(-90deg);
-moz-transform : rotate(-90deg);
}
body{
background-color: #242424;
}
#timers .time{
position: relative; z-index: 1; height: 70px; width: 70px; }
#timers span {
position : absolute;
z-index : 1;
top : 50%;
margin-top : -0.6em;
display : block;
width : 100%;
text-align : center;
height : 1.5em;
color : #528f20;
font : 1.3em Arial;
}
I created a Timer function that will take a duration, a parent element, as well as optional selectors for the canvas and counter. If can
and cnt
aren't specified, and don't exist, it will create them. To the html, I added an extra grouping div so that all of the elements for each timer have a common parent. For the CSS, I changed your naming convention to keep it a bit more dry. Each Timer parent div will have the class "time", but that can be whatever you want. The Timer will assume that the canvas has a class of "timer" and the time output will have a class of "counter". These can also be whatever you want, but you'll have to specify the parameters in that case.