Fabricjs-渐变new fabric.Gradient
var addCircle = function() { var circle = new fabric.Circle({ left: 100, top: 100, radius: 50 })
//渐变样式定义 let gradient = new fabric.Gradient({ type: 'linear', //linear radial gradientUnits: 'pixels', //pixels 百分比 coords: { x1: 0, y1: 0, x2: circle.width, y2: 0, }, colorStops: [ { offset: 0, color: "red" }, { offset: 0.2, color: "orange" }, { offset: 0.4, color: "yellow" }, { offset: 0.6, color: "green" }, { offset: 0.8, color: "blue" }, { offset: 1, color: "purple" } ] }) circle.set('fill', gradient) canvas.add(circle) }
效果:
coords: { x1: 0, y1: circle.width, x2: 0, y2: 0, },
效果:
详解
new fabric.Gradient
/** * Constructor * @param {Object} options Options object with type, coords, gradientUnits and colorStops * @param {Object} [options.type] gradient type linear or radial * @param {Object} [options.gradientUnits] gradient units * @param {Object} [options.offsetX] SVG import compatibility * @param {Object} [options.offsetY] SVG import compatibility * @param {Object[]} options.colorStops contains the colorstops. * @param {Object} options.coords contains the coords of the gradient * @param {Number} [options.coords.x1] X coordiante of the first point for linear or of the focal point for radial * @param {Number} [options.coords.y1] Y coordiante of the first point for linear or of the focal point for radial * @param {Number} [options.coords.x2] X coordiante of the second point for linear or of the center point for radial * @param {Number} [options.coords.y2] Y coordiante of the second point for linear or of the center point for radial * @param {Number} [options.coords.r1] only for radial gradient, radius of the inner circle * @param {Number} [options.coords.r2] only for radial gradient, radius of the external circle * @return {fabric.Gradient} thisArg */
方法:
addColorStop
gradient.addColorStop({ 0.5: 'black' }) circle.set('fill', gradient)
//源码
addColorStop: function(colorStops) {
for (var position in colorStops) {
var color = new fabric.Color(colorStops[position]);
this.colorStops.push({
offset: parseFloat(position),
color: color.toRgb(),
opacity: color.getAlpha()
});
}
return this;
}
toObject
gradient.type2 = '测试属性' gradient.type3 = '测试属性3' let outputObj = gradient.toObject(['type2']) //type2会被同步输出,type3不会 内部调用了populateWithProperties方法
console.log(outputObj)
输出:
toSVG
let outputSVG = gradient.toSVG({ width: 100, height: 100 }) console.log(outputSVG) //下载SVG const a = document.createElement("a"); const blob = new Blob([outputSVG], { type: "image/svg+xml" }); const blobURL = URL.createObjectURL(blob); a.href = blobURL; a.download = "eraser_example.svg"; a.click(); URL.revokeObjectURL(blobURL);
toLive
待定——还没搞明白