使用colorstop绘制非渐变圆

时间:2015-12-01 14:39:39

标签: html5 canvas html5-canvas

如何使用colorstop绘制非渐变圆,如下所示:

enter image description here

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

enter image description here

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();

2 个答案:

答案 0 :(得分:3)

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

 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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

添加这些

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

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