【问题标题】:Drawing non-gradient circle with colorstop用colorstop绘制非渐变圆
【发布时间】:2015-12-01 22:43:48
【问题描述】:

我怎样才能用colorstop画一个非渐变的圆,像这样:

我得到的最接近的是使用径向渐变http://jsfiddle.net/8tdz0bo4/2/

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var x = 100,
    y = 75,
    innerRadius = 1,
    outerRadius = 50,
    radius = 60;

var gradient = ctx.createRadialGradient(x, y, innerRadius, x, y, outerRadius);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'transparent');
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = gradient;
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke();

【问题讨论】:

    标签: html canvas html5-canvas


    【解决方案1】:

    答案很简单:为了避免任何渐变,只需构建几个具有相同开始和结束颜色的步骤,如下所示:

     0.0 red   // first red step 
     0.5 red   // end of first red step
     0.5 blue  // second blue step
     1.0 blue. // end of blue step
    

    有了这个想法,你的代码就变成了:

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    
    var x = 100,
      y = 75,
      innerRadius = 1,
      outerRadius = 50,
      radius = 60;
    
    var gradient = ctx.createRadialGradient(x, y, innerRadius, x, y, outerRadius);
    gradient.addColorStop(0, 'red');
    gradient.addColorStop(0.6, 'red');
    gradient.addColorStop(0.6, 'transparent');
    gradient.addColorStop(1, 'transparent');
    ctx.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.fillStyle = gradient;
    ctx.fill();
    ctx.lineWidth = 2;
    ctx.strokeStyle = 'black';
    ctx.stroke();
    <canvas id='canvas'></canvas>

    【讨论】:

      【解决方案2】:

      添加这些

      gradient.addColorStop(0.2, 'red');
      gradient.addColorStop(0.2, 'transparent');
      

      http://jsfiddle.net/8tdz0bo4/3/

      【讨论】:

        猜你喜欢
        • 2013-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-07
        相关资源
        最近更新 更多