canvas繪製虛線圖表

最近有讀者加我微信諮詢這個問題,如下圖所示: image.png

要實現的效果如下: image.png

其實難度不大,但是考慮一些人員對於canvas不熟悉,還是簡單的介紹下。

其實該圖表,就是一個圓圈外面在套一個圓弧的效果, 主要的難點在於不知道怎麼繪製圓圈的虛線效果。 其實canvas本身已經支持了虛線的繪製,就是一個api調用的事情,api是setLineDash。

示例代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Line Dash</title>
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="600" height="400"></canvas>
    <script>
        var ctx = document.getElementById( 'canvas' ).getContext( '2d' );
        var w = canvas.width,
                h = canvas.height;

        var x = w / 2,
                y = h / 2;
        ctx.save();
        ctx.strokeStyle = "gray";
        ctx.setLineDash([5,5]);
        ctx.lineWidth = 10;
        ctx.beginPath();
        ctx.arc(200,200,75,0,Math.PI *2);
        ctx.stroke();
        ctx.restore();

        ctx.save();
        ctx.beginPath();
        ctx.lineWidth = 12;
        ctx.lineCap = "round";
        ctx.joinCap = "round";
        ctx.strokeStyle = "red";
        ctx.arc(200,200,75,0,-Math.PI/2,Math.PI /2 );
        ctx.stroke();
        ctx.restore();
    </script>
</body>
</html>

繪製效果如下圖所示: result

ps: 後面那個讀者也給我看了下css的實現, css實現這種東西還是太麻煩,一般不建議。 css

關注公衆號“ITMan彪叔” 可以及時收到更多有價值的文章。另外如果對可視化感興趣,可以和我交流,微信541002349.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章