steve steve - 1 month ago 13
HTML Question

Canvas partial circle

So, I have some js code to draw a circle with a specified percentage my issue is that I want the empty part to be filled in with a specified color also.
Area

Here is my code:

HTML:

<!DOCTYPE html>
<html>
<script src="ion.js"></script>
<canvas data-width="5" data-ringcolor="blue" data-filledcolor="1" data-precentage="90" onclick="createNewChart( this, 40 );">
</canvas>
</html>


JS:

function createNewChart( elemnt, radius )
{
if( elemnt.getAttribute( "data-ringcolor" ) && elemnt.getAttribute( "data-filledcolor" ) && elemnt.getAttribute( "data-precentage" ) && elemnt.getAttribute( "data-width" ) )
{
var percentage = Number( elemnt.getAttribute( "data-precentage" ) );

var ctx = elemnt.getContext( "2d" );
ctx.beginPath( );
ctx.arc( 95, 50, radius, 0, ( ( percentage / 100 ) * 2 ) * Math.PI );
ctx.strokeStyle = elemnt.getAttribute( "data-ringcolor" );
ctx.lineWidth = Number( elemnt.getAttribute( "data-width" ) );

ctx.stroke();
}
else
{
alert( "Missing attribute!" );
}
}

Answer

Add another path like this:

function createNewChart( elemnt, radius )
{
    if( elemnt.getAttribute( "data-ringcolor" ) && elemnt.getAttribute( "data-filledcolor" )  && elemnt.getAttribute( "data-precentage" ) && elemnt.getAttribute( "data-width" ) )
    {
        var percentage = Number( elemnt.getAttribute( "data-precentage" ) );

        var ctx = elemnt.getContext( "2d" );
        ctx.beginPath( );
        ctx.arc( 95, 50, radius, 0, ( ( percentage / 100 ) * 2 ) * Math.PI );
        ctx.strokeStyle = elemnt.getAttribute( "data-ringcolor" );
        ctx.lineWidth = Number( elemnt.getAttribute( "data-width" ) );

        ctx.stroke();

        ctx.beginPath( );
        ctx.arc( 95, 50, radius, ( percentage / 100 ) * 2 * Math.PI, 2 * Math.PI );
        ctx.strokeStyle = "red";
        ctx.lineWidth = Number( elemnt.getAttribute( "data-width" ) );

        ctx.stroke();
    }
    else
    {
        alert( "Missing attribute!" );
    }
}