【发布时间】:2016-04-26 10:53:53
【问题描述】:
正如您在此处看到的:http://jsfiddle.net/Da7SP/60/ 我有 64 个馅饼,我希望从中间到边缘有一个径向渐变。 (Live每件都会有不同的颜色)但我没有成功创造出那种效果。
代码如下:
var canvas = window._canvas = new fabric.Canvas('c');
var x=300
, y=300
, totalGates=64
, start=0
, radius=200
, val = 360 / totalGates;
for (var i = 0; i < totalGates; i++) {
createPath(x, y, radius, val*i, (val*i)+val);
}
function createPath (x, y, radius, startAngle, endAngle) {
var flag = (endAngle - startAngle) > 180;
startAngle = (startAngle % 360) * Math.PI / 180;
endAngle = (endAngle % 360) * Math.PI / 180;
var path = 'M '+x+' '+y+' l ' + radius * Math.cos(startAngle) + ' ' + radius * Math.sin(startAngle) +
' A ' + radius + ' ' + radius + ' 0 ' + (+flag) + ' 1 ' + (x + radius * Math.cos(endAngle))+ ' ' + (y + radius * Math.sin(endAngle)) + ' z';
var piePiece = new fabric.Path(path);
piePiece.set({
strokeWidth:0
});
piePiece.setGradient('fill', {
type:'radial',
x1: x,
y1: y,
//x2: x + radius * Math.cos(endAngle),
//y2: y + radius * Math.sin(endAngle),
r1: radius,
r2: 0,
colorStops: {
0: '#000',
1: '#fff',
}
});
canvas.add(piePiece);
}
我认为将 x1 设置为 x 并将 y1 设置为 y 来定义中间坐标和半径就足够了(在我使用 PathGroup 之前)。但现在当我将路径添加到组或直接添加到画布时,渐变看起来完全不同。
那么,如何将 setGradient 与径向渐变一起使用,使其显示为好像整个饼图是一个圆形,它会从中心到边缘
更新: 我注意到,如果我设置 x=0 和 y=0,那么渐变会居中。
更新2: 如果 x1 和 y2 都设置为 0,则从左上角开始绘制渐变,这使得 90 度右下角的渐变看起来不错:http://jsfiddle.net/Da7SP/61/
更新3: 我解决了!这里http://jsfiddle.net/Da7SP/64/ 是你遇到同样问题的小提琴,下面你会看到结果和代码。
这成功了:
x1: x > Math.round(piePiece.left) ? x - piePiece.left : 0,
y1: y > Math.round(piePiece.top) ? y - piePiece.top : 0,
x2: x > Math.round(piePiece.left) ? x - piePiece.left : 0,
y2: y > Math.round(piePiece.top) ? y - piePiece.top : 0,
这是预期的结果:
这里是代码
var canvas = window._canvas = new fabric.Canvas('c');
var x=300
, y=300
, totalGates=64
, start=0
, radius=200
, val = 360 / totalGates;
/* Loops through each gate and prints selected options */
for (var i = 0; i < totalGates; i++) {
createPath(x, y, radius, val*i, (val*i)+val, i);
}
function createPath (x, y, radius, startAngle, endAngle,i ) {
var flag = (endAngle - startAngle) > 180;
startAngle = (startAngle % 360) * Math.PI / 180;
endAngle = (endAngle % 360) * Math.PI / 180;
var path = 'M '+x+' '+y+' l ' + radius * Math.cos(startAngle) + ' ' + radius * Math.sin(startAngle) +
' A ' + radius + ' ' + radius + ' 0 ' + (+flag) + ' 1 ' + (x + radius * Math.cos(endAngle))+ ' ' + (y + radius * Math.sin(endAngle)) + ' z';
var piePiece = new fabric.Path(path);
piePiece.set({
strokeWidth:0
});
piePiece.setGradient('fill', {
type:'radial',
x1: x > Math.round(piePiece.left) ? x - piePiece.left : 0,
y1: y > Math.round(piePiece.top) ? y - piePiece.top : 0,
x2: x > Math.round(piePiece.left) ? x - piePiece.left : 0,
y2: y > Math.round(piePiece.top) ? y - piePiece.top : 0,
r1: radius,
r2: 0,
colorStops: {
0: '#000',
1: '#f0f',
}
});
canvas.add(piePiece);
}
【问题讨论】:
-
你有你想要的图片吗?边缘中间的渐变是什么意思?
-
像这样:jsfiddle.net/Da7SP/62(我刚刚解决了!)
标签: javascript fabricjs radial-gradients