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

标签 jquery html css canvas

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

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

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

这种方法非常有限,我想做一些更灵活的事情。 选择的方法是什么?我找到了两种可能的方法:1) canvas 2) SVG + fill

我尝试过 jCanvas,但没有找到解决方案。应该怎么走?

最佳答案

这是一个使用 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>

关于jquery - 一种虚线圆,用 css/js 改变每个点的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24533718/

相关文章:

css - 字体在IE上不显示

javascript - 动态生成元素时如何避免 ID 冲突

javascript - Highcharts - 使一个点可点击?

javascript - 代码可以在 jsfiddle 中运行,但不能在 html 文档中运行。为什么?

ruby-on-rails - 如何设置 rails f.select 的 "data-"

html - 如何在同一 div 中将 <h1> 对齐到中心并将 <p> 对齐到右侧

jquery - Umbraco7 新后台部分,编辑日期字段,AngularJS

jquery - Laravel Elixir 与 JQuery 和 JQuery UI

html - div 高度内的 div 的问题

html - 搜索带有日历周的 DateTimePicker 组件