如何在圆圈上的不同位置打印不同的颜色?

时间:2014-03-05 21:55:15

标签: canvas html5-canvas

这是我的代码,但是当我在{I}位置设置strokeStyle的新颜色

颜色(新颜色)覆盖我的旧颜色...

我认为问题来自0 - 90 * Math.PI / 180,因为这设置了起始角度(顶部),并且每次圆圈时都会覆盖。但是我无法解决这个问题。

你能帮帮我吗?

像这样......

http://i58.tinypic.com/t8q4vk.png http://i58.tinypic.com/t8q4vk.png

<!DOCTYPE HTML>
    <html>
      <head>
        <style>
          canvas {
            border:1px solid #2C2C2B; /* 1px border around canvas */
          }
        </style>
      </head>
     <body>
        <canvas id="Canvas" width="600" height="250"></canvas>
        <script>
          var i = 0;    
          window.onload = function(){
            setInterval(function(){
             if(i < 6) init();
            },550);

          }
          function init(){
            var canvas = document.getElementById('Canvas');
            var context = canvas.getContext('2d');
            context.beginPath();
            context.arc(100,75,50, 0 - 90 * Math.PI / 180,i - 90 * Math.PI/180, false);
            context.lineWidth = 7;
            if(i < 1.5){ context.strokeStyle = 'blue'}
            else if(i > 1.5 && i <= 3){context.strokeStyle = 'red';}
            else if(i > 3 && i <= 4.5){context.strokeStyle = 'blue';}
            else{ context.strokeStyle = 'red';}
            context.stroke();
            i+=0.1;
          }
        </script>
      </body>
    </html>  

1 个答案:

答案 0 :(得分:0)

关键是将弧分割成小块,因为每个笔划只能有一种颜色。还记得使用PI和角度检查弧度。

Live demo

<强>结果:

Snapshot

var i = 0;
var step = 0.1;
var canvas = document.getElementById('Canvas');
var context = canvas.getContext('2d');

(function init() {
    context.beginPath();

    // use i directly as it is already in radians, draw only a small segment
    context.arc(100, 75, 50, i - 0.5 * Math.PI, i - 0.5 * Math.PI + step);
    context.lineWidth = 7;

    // remember to use PI (it makes it easier at least)
    if (i <= 0.5 * Math.PI) {
        context.strokeStyle = 'blue'
    }
    else if (i > 0.5 * Math.PI && i <= Math.PI) {
        context.strokeStyle = 'red';
    }
    else if (i > Math.PI && i <= 1.5 * Math.PI) {
        context.strokeStyle = 'blue';
    }
    else {
        context.strokeStyle = 'red';
    }

    context.stroke();

    i += step;

    // check here and use setTimeout
    if (i <= 2 * Math.PI) setTimeout(init, 150);
})();

注意我已将setInterval替换为setTimeout。这样,当没有其他事情要做时,计时器将停止 - 否则计时器将在后台运行不必要。

对于非常流畅的动画,您可以将setTimeout替换为requestAnimationFrame并使用i的较低步长值:

Demo using rAF

var i = 0;
var step = 0.01;  // lower value

(function init() {

    // ... rest of code identical

    if (i <= 2 * Math.PI) requestAnimationFrame(init);
})();