jonas
jonas

Reputation: 125

kind of dotted circle, change color of each dot with css/js

i would like to display this image https://i.sstatic.net/aWrK9.png (close to a half circle) and be able to change the color of each area.

At the moment i've solved the problem by creating different pictures and changing them with jquery (css)

$('.img').css('background-image','url(img/img_'+ num + '.png)');

This method in very restricted and i would like to do something more flexible. What would be the method of choice? I found two possible ways: 1) canvas 2) SVG + fill

I've tried jCanvas, but i didnt find a solution. What would be the way to go?

Upvotes: 0

Views: 1457

Answers (1)

markE
markE

Reputation: 105035

Here's one example using html canvas.

enter image description here

Annotated code and a Demo: http://jsfiddle.net/m1erickson/QEP8x/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    // canvas related references
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    // set the line width used to draw the arc segments
    ctx.lineWidth=20;

    // variables related to drawing arc segments
    var PI=Math.PI;
    var PI2=PI*2;
    var cx=150;
    var cy=150;
    var radius=100;
    var arcRadians=PI2/14;
    var spacingRadians=PI2/70;
    var arcCount=7;
    var currentAngle=PI;

    // Draw arc segments from a centerpoint at a specified radius (cx,cy,radius)
    // Draw the specified count of arc segments (arcCount)
    // from the current radian angle (currentAngle)
    // with each segment having the specified arc (arcRadians)
    // and reducing each segment to allow specified spacing (spacingRadians)
    for(var i=0;i<arcCount;i++){

        // calculate the starting and ending angle of an arc segment
        // allow for spacing between arcs
        var startingAngle=currentAngle;
        var endingAngle=startingAngle+arcRadians-spacingRadians;

        // draw one arc segment
        ctx.beginPath();
        ctx.arc(cx,cy,radius,startingAngle,endingAngle);
        ctx.strokeStyle=randomColor();
        ctx.stroke();

        // increment the current angle for the next arc
        currentAngle+=arcRadians;

    }

    // utility function -- generate a random color
    function randomColor(){ 
        return('#'+Math.floor(Math.random()*16777215).toString(16));
    }


}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Upvotes: 1

Related Questions