@nmmty/lazycanvas
Version:
A simple way to interact with @napi-rs/canvas in an advanced way!
83 lines (82 loc) • 2.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Pattern = void 0;
const types_1 = require("../../types");
const LazyCanvas_1 = require("../LazyCanvas");
const canvas_1 = require("@napi-rs/canvas");
const Exporter_1 = require("./Exporter");
const LazyUtil_1 = require("../../utils/LazyUtil");
/**
* Class representing a pattern with properties and methods to manipulate it.
*/
class Pattern {
/**
* The type of fill, which is always `Pattern`.
*/
fillType = types_1.FillType.Pattern;
/**
* The type of the pattern (e.g., repeat, no-repeat, etc.).
*/
type;
/**
* The source of the pattern, which can be a string (URL or path) or a LazyCanvas instance.
*/
src;
/**
* Constructs a new Pattern instance.
* @param opts {Object} - Optional properties for the pattern.
* @param opts.props {IPattern} - The pattern properties.
*/
constructor(opts) {
this.type = opts?.props?.type || types_1.PatternType.Repeat;
this.src = opts?.props?.src || '';
}
/**
* Sets the type of the pattern.
* @param type {AnyPatternType} - The type of the pattern (e.g., repeat, no-repeat).
* @returns {this} The current instance for chaining.
*/
setType(type) {
this.type = type;
return this;
}
/**
* Sets the source of the pattern.
* @param src {string | LazyCanvas} - The source of the pattern, which can be a string (URL or path) or a LazyCanvas instance.
* @returns {this} The current instance for chaining.
*/
setSrc(src) {
this.src = src;
return this;
}
/**
* Draws the pattern on a canvas context.
* @param ctx {SKRSContext2D} - The canvas rendering context.
* @returns {Promise<CanvasPattern>} The created pattern.
*/
async draw(ctx) {
if (!this.src)
throw new LazyUtil_1.LazyError('Pattern source is not set');
if (this.src instanceof LazyCanvas_1.LazyCanvas) {
return ctx.createPattern((await this.src.manager.render.render('canvas')), this.type);
}
return ctx.createPattern(await (0, canvas_1.loadImage)(this.src), this.type);
}
/**
* Converts the Pattern instance to a JSON representation.
* @returns {IPattern} The JSON representation of the pattern.
*/
toJSON() {
let src = this.src;
if (this.src instanceof LazyCanvas_1.LazyCanvas) {
// @ts-ignore
src = new Exporter_1.Exporter(this.src).syncExport('json');
}
return {
fillType: this.fillType,
type: this.type,
src: src
};
}
}
exports.Pattern = Pattern;