@nmmty/lazycanvas
Version:
A simple way to interact with @napi-rs/canvas in an advanced way!
76 lines (75 loc) • 2.69 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Gradient = void 0;
const enum_1 = require("../../types/enum");
const utils_1 = require("../../utils/utils");
class Gradient {
type;
points;
stops;
constructor() {
this.type = enum_1.GradientType.Linear;
this.points = [];
this.stops = [];
}
/**
* Set the type of the gradient
* @param type {AnyGradientType} - The `type` of the gradient. Can be `linear`, `radial`, or `conic`
*/
setType(type) {
this.type = type;
return this;
}
/**
* Add a point to the gradient
* @param points {GradientPoint[]} - The `points` to add to the gradient. `{ x: number, y: number }`
*/
addPoints(...points) {
this.points.push(...points);
return this;
}
/**
* Add a stop to the gradient
* @param stops {GradientColorStop[]} - The `stops` to add to the gradient. `{ color: string, position: number }`
*/
addStops(...stops) {
this.stops.push(...stops);
return this;
}
draw(ctx) {
let gradientData = this.toJSON();
let gradient;
switch (gradientData.type) {
case enum_1.GradientType.Linear:
case "linear":
gradient = ctx.createLinearGradient(gradientData.points[0].x, gradientData.points[0].y, gradientData.points[1].x, gradientData.points[1].y);
break;
case enum_1.GradientType.Radial:
case "radial":
gradient = ctx.createRadialGradient(gradientData.points[0].x, gradientData.points[0].y, (gradientData.points[0].r || 0), (gradientData.points[1].x || gradientData.points[0].x), (gradientData.points[1].y || gradientData.points[0].y), (gradientData.points[1].r || 0));
break;
case enum_1.GradientType.Conic:
case "conic":
gradient = ctx.createConicGradient((gradientData.points[0].startAngle || 0), gradientData.points[0].x, gradientData.points[0].y);
break;
default:
gradient = ctx.createLinearGradient(gradientData.points[0].x, gradientData.points[0].y, gradientData.points[1].x, gradientData.points[1].y);
break;
}
for (let stop of gradientData.stops) {
gradient.addColorStop(stop.offset, (0, utils_1.parseHex)(stop.color));
}
return gradient;
}
/**
* @returns {IGradient}
*/
toJSON() {
return {
type: this.type,
points: this.points,
stops: this.stops,
};
}
}
exports.Gradient = Gradient;