import Event from '../../typings/event'; import { getAuthorize, setAuthorize } from '../../utils/getAuthorize'; import Element, { EventType, TagName } from './Element/base'; import Image from './Element/Image'; import Text from './Element/Text'; import View from './Element/View'; interface Callback { success?: (res: T) => void; fail?: () => void; } interface Option { /** 缩放倍率 */ scale: number; /** 设计图上的宽度 */ designWidth: number; /** 设计图上的高度 */ designHeight: number; } const isIOS9 = wx.getSystemInfoSync().system.indexOf('iOS 9.') === 0; class Paint { /** * @param scale 缩放倍率 */ constructor(option: Option) { this._scale = isIOS9 ? 2 : option.scale; this.designWidth = option.designWidth; this.designHeight = option.designHeight; } /** 是否已初始化过了 */ // private isInitialized = false; private designWidth = 0; private designHeight = 0; public ctx!: CanvasRenderingContext2D; /** rpx到px的转换率 */ public _rpx = wx.getSystemInfoSync().screenWidth / 750; /** 绘制单位 */ private dpr = wx.getSystemInfoSync().pixelRatio; private _scale: number; /** 缩放 */ public scale!: number; public canvas!: HTMLCanvasElement; private elemnts: Element[] = []; /** 渲染偏移量 */ // private offsetLeft = 0; // /** 渲染偏移量 */ // private offsetTop = 0; /** 初始化Context */ public async init(node: WechatMiniprogram.NodesRef): Promise { return new Promise(async (reslove) => { this.scale = this._rpx * this.dpr; await this.setSize(node); this.ctx = this.canvas.getContext('2d') as CanvasRenderingContext2D; this.ctx.scale(this.scale, this.scale); // if (this.isInitialized === false) { // this.scale = this._rpx * this.dpr; // await this.setSize(node); // this.ctx = this.canvas.getContext('2d') as CanvasRenderingContext2D; // this.ctx.scale(this.scale, this.scale); // this.isInitialized = true; // } reslove(); }); } public async reInit(node: WechatMiniprogram.NodesRef, options: { designWidth: number; designHeight: number }): Promise { this.designWidth = options.designWidth; this.designHeight = options.designHeight; return await this.init(node); } public setSize(node: WechatMiniprogram.NodesRef) { return new Promise((reslove) => { node.fields({ node: true, size: true }).exec((res) => { this.canvas = res[0].node; this.canvas.width = res[0].width * this._scale; this.canvas.height = res[0].height * this._scale; reslove(null); }); }); } /** 将设计图的坐标映射到画布上 */ public mapping = (type: 'x' | 'y', value: number) => { if (type === 'x') { return (value / this.designWidth) * this.canvas.width / this.scale; } else { return (value / this.designHeight) * this.canvas.height / this.scale; } } // public rpx( value: number) { // // return value * this._scale * this._rpx; // } // public setScale(value: number) { // const scale = this.rpx * this.dpr * value; // this.scale = value; // this.canvas.width *= scale; // this.canvas.height *= scale; // this.ctx.scale(scale, scale); // } public createElement(tagName: 'view'): View; public createElement(tagName: 'text'): Text; public createElement(tagName: 'image'): Image; public createElement(tagName: TagName, options?: any) { switch (tagName) { case 'image': return new Image(this.canvas, 1); case 'text': return new Text(this.canvas, this.ctx, 1); case 'view': return new View(this.canvas, 1); } } // private async ecahElements(elements: Element | Element[], callback: (element: Element) => Promise): Promise { // if (Array.isArray(elements)) { // for (let i = 0; i < elements.length; i++) { // await this.ecahElements(elements[i], callback); // } // } else { // await callback(elements); // } // } /** 更新渲染到的位置 */ // private updateOffset(element: Element) { // this.offsetTop += element.style.getComputedStyle('height')!; // console.log('updateOffset', this.offsetLeft, this.offsetTop) // } public render(elements: Element[]): void { this.elemnts = elements; for (let i = 0; i < elements.length; i++) { const element = elements[i]; // if (!element.parent) { // element.setSize(); // element.style.x = this.offsetLeft; // element.style.y = this.offsetTop; // } // element.render(this.ctx, { x: this.offsetLeft, y: this.offsetTop }); // this.updateOffset(element); element.render(this.ctx); } } /** 保存到临时相册 */ public async canvasToTempFilePath(params?: Callback): Promise { const width = this.canvas.width; const height = this.canvas.height; return new Promise((reslove) => { wx.canvasToTempFilePath({ x: 0, y: 0, width: width, height: height , destWidth: width, destHeight: height, canvas: this.canvas as any, fileType: 'png', success: (res) => { if (params?.success) { params?.success(res); } reslove(res); }, fail(res) { if (params?.fail) { params.fail(); } console.error(res); reslove(null); } }); }); } /** 保存到系统相册 */ public save(params?: Callback) { const scope = 'scope.writePhotosAlbum'; const success = (res: WechatMiniprogram.CanvasToTempFilePathSuccessCallbackResult) => { wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success() { wx.showToast({ title: '图片保存成功', icon: 'success' }); if (params?.success) { params.success(null); } } }); }; wx.showLoading({ title: '保存中...', mask: true }); getAuthorize({ scope: scope, success: () => { this.canvasToTempFilePath({ success: success, fail: params?.fail }); }, getSettingFail: () => { wx.showToast({ title: '图片保存失败,需要授权', icon: 'none', duration: 3000 }); }, authorizeFail: () => { setAuthorize({ scope: scope, modalContent: '保存图片需要开启授权', success: success, fail: params?.fail }); wx.showToast({ title: '图片保存失败,需要授权', icon: 'none', duration: 3000 }); }, finally: () => { wx.hideLoading(); } }); } /** 预览 */ public preview(params?: Callback) { this.canvasToTempFilePath({ success: (res) => { const tempFilePath = res.tempFilePath; if (tempFilePath !== "") { wx.previewImage({ current: res.tempFilePath, urls: [res.tempFilePath], success(res) { if (params?.success) { params.success(res); } }, fail: params?.fail }); } } }); } public triggerEvent(type: EventType, event: Event.Touch) { for (let i = 0; i < this.elemnts.length; i++) { const item = this.elemnts[i]; const style = item.style; const { offsetLeft, offsetTop } = event.currentTarget; const x = style.getComputedStyle('x'); const y = style.getComputedStyle('y'); const width = style.getComputedStyle('width'); const height = style.getComputedStyle('height'); item._events[type].forEach((itemEvent) => { for (let j = 0; j < event.changedTouches.length; j++) { const touch = event.changedTouches[j]; const clientX = (touch.clientX - offsetLeft) * this._scale / this.scale; const clientY = (touch.clientY - offsetTop) * this._scale / this.scale; if (clientX >= x && clientX <= x + width && clientY >= y && clientY <= y + height) { itemEvent(event); } } }); } } } export { Element }; export default Paint;