import { BaseModel } from './base-model'; import { MessageType } from '../core/message-type'; import { Servicer } from '../servicer/servicer'; import { loadImage, loadImageData } from '../utils/load-image'; import { FillType } from '../enums/fill-type'; const commands = MessageType.source; /** * 数据源 */ export class Source extends BaseModel { public fillType: FillType = FillType.NONE; private _width: number = 0; private _height: number = 0; constructor( sourceId: string, servicer: Servicer ) { super(sourceId, servicer); } get width() { return this._width; } get height() { return this._height; } async destory(): Promise { await this.servicer.do(commands.destory, [this.id]); } /** * 将像素数据设置到数据源上 * @param pixels - 像素数据 * @param width - 宽度 * @param height - 高度 */ async setPixels(pixels: ArrayLike, width: number, height: number): Promise { this._width = width; this._height = height; await this.servicer.do(commands.setPixels, [this.id, pixels, width, height]); } /** * 将远端服务上的图片加载并设置到数据源上 * @param url - 图片地址 */ async setPixelsFromUrl(url: string) { const image = await loadImage(url); const imageData = loadImageData(image); await this.setPixels(imageData.data, imageData.width, imageData.height); } /** * 将纯色画布设置为数据源 * @param color - 画布颜色 * @param width - 宽度 * @param height - 高度 */ async setPixelsFromColor(color: string, width: number, height: number) { const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const context = canvas.getContext('2d')!; context.fillStyle = color; context.fillRect(0, 0, width, height); const imageData = context.getImageData(0, 0, width, height); await this.setPixels(imageData.data, width, height); } /** * 设置填充方式 * @param fillType - 填充方式 */ async setFillType(fillType: FillType) { this.fillType = fillType; await this.servicer.do(commands.setFillType, [this.id, fillType]); } /** * 设置基于画布宽高与目标宽高比例的裁剪 * @param ratio - 宽高比例 */ async setClipRatio(ratio: number) { await this.servicer.do(commands.setClipRatio, [this.id, ratio]); } /** * 平移数据源 * @param x - x 轴平移量 * @param y - y 轴平移量 * @param z - z 轴平移量 */ async translate(x: number, y: number, z: number) { await this.servicer.do(commands.translate, [this.id, x, y, z]); } /** * 缩放数据源 * @param x - x 轴缩放比 * @param y - y 轴缩放比 * @param z - z 轴缩放比 */ async scale(x: number, y: number, z: number) { await this.servicer.do(commands.scale, [this.id, x, y, z]); } /** * 旋转数据源 * @param x - x 轴旋转角度 * @param y - y 轴旋转角度 * @param z - z 轴旋转角度 */ async rotate(x: number, y: number, z: number) { await this.servicer.do(commands.rotate, [this.id, x, y, z]); } /** * 数据变更时候需要调用该接口通知基类 */ async notifyRefresh() { await this.servicer.do(commands.notifyRefresh, [this.id]); } }