Reputation: 2016
I've implemented a simple progressbar in javascript using the html 5 canvas element. The progressbar should be able to show 100 steps. (0-100%) The progressbar should be able to have variable size, which can bet set by the user. So, for every step I draw a rectangle.
For example: - The progressbar canvas has a width of 100px. - On every step I draw a new one pixel wide block.
The problem: - The progressbar canvas has a width of 550px. - The step-block-size would be 5.5px (550/steps) - I'm unable to draw half pixels. If I use Math.floor or Math.Round the progressbar won't be filled out complete at 100% or it will be "overfilled".
How can I solve that problem?
var percWidth = Math.round(canvas.width / 100);
for (var i = 0; i<= percentage; i++)
{
var r,g,b;
if (i <= 50)
{
r = 255;
g = Math.round((255*i)/50);
b = 0;
}
else
{
r = Math.round((255*(100-i))/50);
g = 255;
b = 0
}
context.fillStyle = "rgb("+r+", "+g+", "+b+")";
context.fillRect((i*percWidth), 0, (1*percWidth), canvas.height);
}
Upvotes: 0
Views: 774
Reputation: 4530
I know this isn't directly applicable to your question -- but is the <progress>
a suitable substitute?
Upvotes: 0
Reputation: 39763
Only round the final result:
context.fillRect(Math.round(i*canvas.width / 100), 0, (percWidth), canvas.height);
Upvotes: 2