一种虚线圆圈,用css / js改变每个点的颜色

时间:2014-07-02 14:25:47

标签: jquery html5 css3 canvas

我想显示此图片http://i.imgur.com/l8fbZM3.png(接近半圈)并能够更改每个区域的颜色。

目前我通过创建不同的图片并使用jquery(css)更改它们来解决问题

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

这种方法非常有限,我想做一些更灵活的事情。 选择的方法是什么?我发现了两种可能的方法:1)画布2)SVG +填充

我尝试过jCanvas,但我找不到解决方案。怎么回事?

1 个答案:

答案 0 :(得分:1)

以下是使用html canvas的一个示例。

enter image description here

带注释的代码和演示: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>