使用 colorstop 绘制非渐变圆
Drawing non-gradient circle with colorstop
如何用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();
添加这些
gradient.addColorStop(0.2, 'red');
gradient.addColorStop(0.2, 'transparent');
答案很简单:为了避免任何渐变,只需构建几个具有相同开始和结束颜色的步骤,如:
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>
如何用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();
添加这些
gradient.addColorStop(0.2, 'red');
gradient.addColorStop(0.2, 'transparent');
答案很简单:为了避免任何渐变,只需构建几个具有相同开始和结束颜色的步骤,如:
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>