import { defaultGradientRange, asVec, ColorSchema, ColorRangSchema, getColorStyle, ColorStyleGradient, } from '@gedit/canvas-draw'; import { SizeSchema } from '@gedit/utils'; export interface TextStyle extends Omit { fill: PIXI.FillInput; dropShadow: boolean | PIXI.TextDropShadow; } interface FillGradient extends PIXI.FillGradient { range: ColorRangSchema; mode: 'fill' | 'lineGradient' | 'radialGradient' | 'conicGradient'; rect: { width: number; height: number; offset: number; contentWidth: number; contentHeight: number; x: number; y: number; }; canvas: HTMLCanvasElement; gradientStops: ColorSchema['colors']; gradient: CanvasGradient; } interface ISpineAtlasMetadata { // If you are downloading an .atlas file, this metadata will go to the Texture loader imageMetadata?: any; // If you already have atlas pages loaded as pixi textures // and want to use that to create the atlas, you can pass them here images?: | PIXI.TextureSource | string | Record; } function getCanvasFillStyle( fillStyle: PIXI.ConvertedFillStyle, context: CanvasRenderingContext2D ): string | CanvasGradient | CanvasPattern { const { fill: f } = fillStyle; const fill = f as FillGradient; if (fill instanceof PIXI.FillGradient) { return fill.gradient; // const t = getColorStyle( // context, // { // colors: fill.gradientStops, // range: fill.range, // mode: fill.mode, // }, // fill.rect.width, // fill.rect.height // ) as ColorStyleGradient; // return t.color as CanvasGradient; } return PIXI.getCanvasFillStyle(fillStyle, context); } export const fixCanvasTextSystem = () => { // const gCanvas: HTMLCanvasElement = document.createElement('canvas'); // gCanvas.style.position = 'absolute'; // gCanvas.style.top = '0'; // gCanvas.style.left = '0'; // gCanvas.style.zIndex = '999999'; // gCanvas.style.backgroundColor = 'red'; // document.body.appendChild(gCanvas); // const gContext = gCanvas.getContext('2d')!; class CanvasTextSystem extends PIXI.CanvasTextSystem { public getTexture( text: string, resolution: number, style: PIXI.TextStyle, textKey: string ): PIXI.Texture; public getTexture(options: PIXI.TextOptions): PIXI.Texture; public getTexture( options: PIXI.TextOptions | string, resolution?: number, style?: PIXI.TextStyle, _textKey?: string ): PIXI.Texture { if (typeof options === 'string') { // #if _DEBUG PIXI.deprecation( '8.0.0', 'CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments' ); // #endif options = { text: options, style, resolution, }; } if (!(options.style instanceof PIXI.TextStyle)) { options.style = new PIXI.TextStyle(options.style); } const { texture, canvasAndContext } = this.createTextureAndCanvas( options as { text: string; style: PIXI.TextStyle; resolution?: number } ); // @ts-ignore this._renderer.texture.initSource(texture._source); PIXI.CanvasPool.returnCanvasAndContext(canvasAndContext); return texture; } drawLetterSpacing( text: string, style: PIXI.TextStyle, canvasAndContext: PIXI.CanvasAndContext, x: number, y: number, isStroke = false ): void { const { context } = canvasAndContext; // letterSpacing of 0 means normal const letterSpacing = style.letterSpacing; let useExperimentalLetterSpacing = false; if (PIXI.CanvasTextMetrics.experimentalLetterSpacingSupported) { if (PIXI.CanvasTextMetrics.experimentalLetterSpacing) { context.letterSpacing = `${letterSpacing}px`; context.textLetterSpacing = `${letterSpacing}px`; useExperimentalLetterSpacing = true; } else { context.letterSpacing = '0px'; context.textLetterSpacing = '0px'; } } if (letterSpacing === 0 || useExperimentalLetterSpacing) { if (isStroke) { context.strokeText(text, x, y); } else { context.fillText(text, x, y); } return; } let currentPosition = x; const stringArray = PIXI.CanvasTextMetrics.graphemeSegmenter(text); let previousWidth = context.measureText(text).width; let currentWidth = 0; for (let i = 0; i < stringArray.length; ++i) { const currentChar = stringArray[i]; if (isStroke) { context.strokeText(currentChar, currentPosition, y); } else { context.fillText(currentChar, currentPosition, y); } let textStr = ''; for (let j = i + 1; j < stringArray.length; ++j) { textStr += stringArray[j]; } currentWidth = context.measureText(textStr).width; currentPosition += previousWidth - currentWidth + letterSpacing; previousWidth = currentWidth; } } getManagedTexture(text: PIXI.Text): PIXI.Texture { // @ts-ignore text._resolution = text._autoResolution ? // @ts-ignore this._renderer.resolution : text.resolution; // @ts-ignore const textKey = text.styleKey; // @ts-ignore if (this._activeTextures[textKey]) { // @ts-ignore this._increaseReferenceCount(textKey); // @ts-ignore return this._activeTextures[textKey].texture; } const { texture, canvasAndContext } = this.createTextureAndCanvas(text); // @ts-ignore this._activeTextures[textKey] = { canvasAndContext, texture, usageCount: 1, }; return texture; } createTextureAndCanvas(options: { text: string; style: PIXI.TextStyle; resolution?: number; }): { texture: PIXI.Texture; canvasAndContext: PIXI.CanvasAndContext } { const { text, style } = options; // @ts-ignore const resolution = options.resolution ?? this._renderer.resolution; // create a canvas with the word hello on it const measured = PIXI.CanvasTextMetrics.measureText(text || ' ', style); const offset = style.padding + (style.dropShadow?.distance ?? 0) + (style.dropShadow?.blur ?? 0) + (style._stroke?.width ?? 0) + (style.fontStyle === 'italic' ? style.fontSize : 0); const width = Math.ceil( Math.ceil(Math.max(1, measured.width) + offset * 2) * resolution ); const height = Math.ceil( Math.ceil(Math.max(1, measured.height) + offset * 2) * resolution ); const canvasAndContext = PIXI.CanvasPool.getOptimalCanvasAndContext( width, height ); // create a texture from the canvas const { canvas } = canvasAndContext; this.renderTextToCanvas( text, style, resolution, canvasAndContext, measured ); const texture = PIXI.getPo2TextureFromSource( canvas, width, height, resolution ); if (style.trim) { const trimmed = PIXI.getCanvasBoundingBox(canvas, resolution); texture.frame.copyFrom(trimmed); texture.updateUvs(); } return { texture, canvasAndContext }; } renderTextToCanvas( text: string, style: PIXI.TextStyle, resolution: number, canvasAndContext: PIXI.CanvasAndContext, _measured?: PIXI.CanvasTextMetrics ): void { const strokeWidth = style._stroke?.width ?? 0; const { textBox = { x: 0, y: 0, width: 0, height: 0, offsetX: 0, offsetY: 0 }, } = style.fill as PIXI.FillStyle; const fill = style._fill.fill as FillGradient; const offset = style.padding + (strokeWidth ?? 0) + (style.dropShadow?.distance ?? 0) + (style.dropShadow?.blur ?? 0) + (style.fontStyle === 'italic' ? style.fontSize : 0); const gCanvas = fill?.canvas; const gContext = fill?.canvas.getContext('2d')!; const { canvas, context } = canvasAndContext; const font = PIXI.fontStringFromTextStyle(style); const measured = _measured || PIXI.CanvasTextMetrics.measureText(text || ' ', style); const lines = measured.lines; const lineHeight = measured.lineHeight; const lineWidths = measured.lineWidths; const maxLineWidth = measured.maxLineWidth; const fontProperties = measured.fontProperties; context.resetTransform(); // gContext.resetTransform(); context.scale(resolution, resolution); // gContext.scale(resolution, resolution); context.clearRect(0, 0, canvas.width, canvas.height); gContext?.clearRect(0, 0, gCanvas.width, gCanvas.height); // set stroke styles.. if (style._stroke?.width) { const strokeStyle = style._stroke; context.lineWidth = strokeStyle.width; context.miterLimit = strokeStyle.miterLimit; context.lineJoin = strokeStyle.join; context.lineCap = strokeStyle.cap; } // return; context.font = font; let linePositionX: number; let linePositionY: number; const passesCount = style.dropShadow ? 2 : 1; for (let i = 0; i < passesCount; ++i) { const isShadowPass = style.dropShadow && i === 0; const dsOffsetText = isShadowPass ? Math.ceil(Math.max(1, canvas.height) + style.padding * 2) : 0; const dsOffsetShadow = dsOffsetText * resolution; if (isShadowPass) { context.fillStyle = 'black'; context.strokeStyle = 'black'; const shadowOptions = style.dropShadow; const dropShadowColor = shadowOptions.color; const dropShadowAlpha = shadowOptions.alpha; context.shadowColor = PIXI.Color.shared .setValue(dropShadowColor) .setAlpha(dropShadowAlpha) .toRgbaString(); const dropShadowBlur = shadowOptions.blur * resolution; const dropShadowDistance = shadowOptions.distance * resolution; context.shadowBlur = dropShadowBlur; context.shadowOffsetX = Math.cos(shadowOptions.angle) * dropShadowDistance; context.shadowOffsetY = Math.sin(shadowOptions.angle) * dropShadowDistance + dsOffsetShadow; } else { // context.globalAlpha = style._fill?.alpha ?? 1; if (style._fill) { context.fillStyle = getCanvasFillStyle( style._fill, context as CanvasRenderingContext2D ); const fill = style._fill.fill as FillGradient; if ( fill instanceof PIXI.FillGradient && fill.mode === 'radialGradient' ) { // 重新绘制文字 gCanvas.width = canvas.width; gCanvas.height = canvas.height; gContext.font = font; gContext.fillStyle = context.fillStyle; } } if (style._stroke?.width) { context.strokeStyle = getCanvasFillStyle( style._stroke, context as CanvasRenderingContext2D ); } context.shadowColor = 'black'; } let linePositionYShift = (lineHeight - fontProperties.fontSize) / 2; if (lineHeight - fontProperties.fontSize < 0) { linePositionYShift = 0; } context.beginPath(); context.globalAlpha = style._stroke?.alpha ?? 1; // 先画完线,避免描边太大,遮挡文字 for (let i = 0; i < lines.length; i++) { linePositionX = offset; linePositionY = i * lineHeight + fontProperties.ascent + linePositionYShift + offset; if (style.align === 'right') { linePositionX += maxLineWidth - lineWidths[i]; } else if (style.align === 'center') { linePositionX += (maxLineWidth - lineWidths[i]) / 2; } if (style._stroke?.width) { this.drawLetterSpacing( lines[i], style, canvasAndContext, linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true ); } } context.beginPath(); context.globalAlpha = style._fill?.alpha ?? 1; // draw lines line by line for (let i = 0; i < lines.length; i++) { linePositionX = offset; linePositionY = i * lineHeight + fontProperties.ascent + linePositionYShift + offset; if (style.align === 'right') { linePositionX += maxLineWidth - lineWidths[i]; } else if (style.align === 'center') { linePositionX += (maxLineWidth - lineWidths[i]) / 2; } const ly = i * lineHeight; if ( (ly < textBox.offsetY - lineHeight || ly > textBox.offsetY + textBox.height) && fill ) { continue; } if ( ((style.dropShadow?.distance || style.dropShadow?.blur) && !style._stroke.width) || (style._fill !== undefined && !( fill instanceof PIXI.FillGradient && fill.mode === 'radialGradient' )) ) { this.drawLetterSpacing( lines[i], style, canvasAndContext, linePositionX + style.padding, linePositionY + style.padding - dsOffsetText ); } if (style._fill !== undefined) { // 圆形渐变需要调整 transform;重新绘制文字 if ( fill instanceof PIXI.FillGradient && fill.mode === 'radialGradient' ) { gContext.fillStyle = 'black'; this.drawLetterSpacing( lines[i], style, { canvas: gCanvas, context: gContext }, linePositionX + style.padding, linePositionY + style.padding - dsOffsetText ); } else if (!fill) { this.drawLetterSpacing( lines[i], style, canvasAndContext, linePositionX + style.padding, linePositionY + style.padding - dsOffsetText ); } } } if ( style._fill !== undefined && fill instanceof PIXI.FillGradient && fill.mode === 'radialGradient' ) { gContext.fillStyle = context.fillStyle; gContext.save(); gContext.rect(0, 0, gCanvas.width, gCanvas.height); const contentWidth = fill.rect.width; const contentHeight = fill.rect.height; const { range } = fill; let { w = defaultGradientRange.w, h = defaultGradientRange.h, lx = defaultGradientRange.lx, ly = defaultGradientRange.ly, lx2 = defaultGradientRange.lx2, ly2 = defaultGradientRange.ly2, } = range || {}; // 需要转换成实际坐标;不然宽高不同会被压缩; lx = lx * contentWidth; ly = ly * contentHeight; lx2 = lx2 * contentWidth; ly2 = ly2 * contentHeight; const { ang } = asVec({ x: lx, y: ly }, { x: lx2, y: ly2 }); gContext.translate( lx + offset - textBox.offsetX, ly + offset + textBox.offsetY ); gContext.rotate(ang + Math.PI / 2); gContext.scale(w, h); gContext.translate( -lx - offset + textBox.offsetX, -ly - offset - textBox.offsetY ); gContext.globalCompositeOperation = 'source-in'; gContext.fill(); gContext.setTransform(); // gContext.putImageData(radialDrawData, 0, 0); context.drawImage(gCanvas, 0, 0); gContext.globalCompositeOperation = 'source-over'; } } } } class FillGradientClass extends PIXI.FillGradient { range: ColorRangSchema; texture: PIXI.Texture; transform: PIXI.Matrix; gradient: CanvasGradient; gradientStops: { offset: number; color: string }[] = []; constructor( public canvas: HTMLCanvasElement, public rect: { width: number; height: number; offset: number; textX: number; textY: number; }, public mode: 'fill' | 'lineGradient' | 'radialGradient' | 'conicGradient', range?: ColorRangSchema ) { const r = { ...defaultGradientRange, ...range }; super( r.lx * rect.width, r.ly * rect.height, r.lx2 * rect.width, r.lx2 * rect.height ); this.range = r; } addColorStop(offset: number, color: string): this { this.gradientStops.push({ offset, color }); return this; } buildLinearGradient(): void { // const width = this.defaultTextureSize; // const height = this.defaultTextureSize; const { width, height, offset, textX, textY } = this.rect; this.canvas.width = width + offset * 2; this.canvas.height = height + offset * 2; const ctx = this.canvas.getContext('2d')!; // ctx.clearRect(0, 0, width, height); const t = getColorStyle( ctx, { colors: this.gradientStops as ColorSchema['colors'], range: this.range, mode: this.mode, }, width, height, offset - textX, offset + textY ) as ColorStyleGradient; this.gradient = t.color as CanvasGradient; ctx.fillStyle = this.gradient; // ctx.fillRect(0, 0, width, height); this.texture = new PIXI.Texture({ source: new PIXI.CanvasSource({ resource: this.canvas, transparent: false, }), }); const m = new PIXI.Matrix(); this.transform = m; } } PIXI.extensions.remove(PIXI.CanvasTextSystem); PIXI.extensions.add(CanvasTextSystem); PIXI.FillGradientClass = FillGradientClass; }; export const getFillGradient = ( canvas: HTMLCanvasElement, size: SizeSchema & { id?: string; x: number; y: number }, data: ColorSchema, boundOffset: number ) => { // @ts-ignore const fill = new PIXI.FillGradientClass( canvas, { width: size.width, height: size.height, offset: boundOffset, textX: size.x, textY: size.y, }, data.mode, data.range ); /* const r = { ...defaultGradientRange, ...data.range }; const fill = new PIXI.FillGradient( r.lx * rect.width, r.ly * rect.height, r.lx2 * rect.width, r.lx2 * rect.height ); */ data.colors.forEach(color => { fill.addColorStop(color.offset, color.color); }); return (fill as unknown) as PIXI.FillGradient; }; export const fixPIXIAssetsLoader = () => { const loadBlob = { extension: { type: PIXI.ExtensionType.LoadParser, priority: PIXI.LoaderParserPriority.Low, }, name: 'loadBlob', test: (url: string) => { const fileName = url.split('/').pop()?.split('?')[0]; return !fileName?.match(/.(jpg|jpeg|webp|png|svg|mp3|mp4|json|txt)$/); }, // 保底都走 blob 加载 async load( url: string, asset: PIXI.ResolvedAsset, loader: PIXI.Loader ): Promise { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'blob'; xhr.onload = () => { const blob = xhr.response; if (blob.type.match(/^image/)) { resolve(PIXI.loadTextures.load?.(url, asset, loader)); } resolve(blob as any); }; xhr.send(); }); }, unload(t: any): void { if (t instanceof PIXI.Texture) { t.destroy(true); } }, }; // satisfies PIXI.LoaderParser; PIXI.extensions.add(loadBlob); Object.defineProperty(PIXI.loadVideoTextures, 'load', { value: async ( url: string, asset: PIXI.ResolvedAsset, loader: PIXI.Loader ) => { const options: PIXI.VideoSourceOptions = { ...PIXI.VideoSource.defaultOptions, resolution: asset.data?.resolution || PIXI.getResolutionOfUrl(url), alphaMode: asset.data?.alphaMode || (await PIXI.detectVideoAlphaMode()), ...asset.data, autoLoad: true, autoPlay: true, playsinline: true, muted: true, }; const videoElement = document.createElement('video'); const attributeMap = { preload: options.autoLoad !== false ? 'auto' : undefined, 'webkit-playsinline': options.playsinline !== false ? '' : undefined, playsinline: options.playsinline !== false ? '' : undefined, muted: options.muted === true ? '' : undefined, loop: options.loop === true ? '' : undefined, autoplay: options.autoPlay !== false ? '' : undefined, }; Object.keys(attributeMap).forEach((key: keyof typeof attributeMap) => { const value = attributeMap[key]; if (value !== undefined) videoElement.setAttribute(key, value); }); if (options.muted === true) { videoElement.muted = true; } PIXI.crossOrigin(videoElement, url, options.crossorigin); const sourceElement = document.createElement('source'); let mime: string | undefined; if (url.startsWith('data:')) { mime = url.slice(5, url.indexOf(';')); } else if (!url.startsWith('blob:')) { const ext = url .split('?')[0] .slice(url.lastIndexOf('.') + 1) .toLowerCase(); mime = PIXI.VideoSource.MIME_TYPES[ext] || `video/${ext}`; } sourceElement.src = url; if (mime) { sourceElement.type = mime; } videoElement.pause(); return new Promise(resolve => { const onCanPlay = async () => { const base = new PIXI.VideoSource({ ...options, resource: videoElement, }); videoElement.removeEventListener('canplaythrough', onCanPlay); if (asset.data?.preload) { await PIXI.preloadVideo(videoElement); } resolve(PIXI.createTexture(base, loader, url)); }; videoElement.addEventListener('canplaythrough', onCanPlay); videoElement.appendChild(sourceElement); // 判断是微信, 直接返回加载完成,不支持预加载 if ( // @ts-ignore window.WeixinJSBridge || navigator.userAgent.match(/micromessenger/gi) ) { onCanPlay(); } }); }, configurable: true, }); const spineTextureAtlasLoader = PIXI.Assets.loader.parsers.find(c => { // @ts-ignore const name = c.name || c.extension?.name; return name === 'spineTextureAtlasLoader'; }); if (spineTextureAtlasLoader) { spineTextureAtlasLoader.parse = async function parse( asset: string, options: PIXI.ResolvedAsset, loader: PIXI.Loader ): Promise { const metadata: ISpineAtlasMetadata = options.data || {}; let basePath = PIXI.path.dirname(options.src as string); if (basePath && basePath.lastIndexOf('/') !== basePath.length - 1) { basePath += '/'; } const retval = new spine.TextureAtlas(asset); if ( metadata.images instanceof PIXI.TextureSource || typeof metadata.images === 'string' ) { const pixiTexture = metadata.images; metadata.images = {} as Record; metadata.images[retval.pages[0].name] = pixiTexture; } const textureLoadingPromises: Promise[] = []; for (const page of retval.pages) { const pageName = page.name; const providedPage = metadata?.images ? metadata.images[pageName] : undefined; if (providedPage instanceof PIXI.TextureSource) { page.setTexture(spine.SpineTexture.from(providedPage) as any); } else { const basePathArray = pageName.match(/^\/\//) ? ['https:'] : basePath.split(PIXI.path.sep); const url: string = providedPage ?? (PIXI.Assets.resolver.resolveUrl(options.data.image) as string) ?? PIXI.path.normalize( [...basePathArray, pageName].join(PIXI.path.sep) ); const assetsToLoadIn = { src: url, data: { ...metadata.imageMetadata, alphaMode: page.pma ? 'premultiplied-alpha' : 'premultiply-alpha-on-upload', }, }; const pixiPromise = loader .load(assetsToLoadIn) .then(texture => { page.setTexture(spine.SpineTexture.from(texture.source) as any); }); textureLoadingPromises.push(pixiPromise); } } await Promise.all(textureLoadingPromises); return retval; }; } // 修复 video 加载后预览图黑屏问题; // https://github.com/pixijs/pixijs/blob/v6.5.8/packages/loaders/src/LoaderResource.ts#L717 // https://github.com/pixijs/pixijs/blob/dev/packages/core/src/textures/resources/VideoResource.ts#L79 // @ts-ignore /* class NewLoaderResource extends PIXI.LoaderResource { // @ts-ignore // eslint-disable-next-line @typescript-eslint/tslint/config private _loadSourceElement(type: string) { // @ts-ignore super._loadSourceElement(type); if (this.data && type === 'video') { this.data.setAttribute('preload', 'auto'); this.data.setAttribute('autoplay', 'true'); this.data.setAttribute('muted', 'true'); this.data.setAttribute('webkit-playsinline', 'true'); this.data.setAttribute('playsinline', 'true'); this.data.pause(); // 判断是微信, 直接返回加载完成,不支持预加载 // @ts-ignore if ( window.WeixinJSBridge || navigator.userAgent.match(/micromessenger/gi) ) { // @ts-ignore this._boundComplete(); } } } } */ // @ts-ignore // PIXI.LoaderResource = NewLoaderResource; }; export const fixTextureMultiplyAlpha = (multiplyAlpha?: boolean) => { // 修复 getPixels 方法 // github issues: https://github.com/pixijs/pixijs/issues/10930 const BYTES_PER_PIXEL = 4; Object.defineProperty(PIXI.GlTextureSystem.prototype, 'getPixels', { value(texture: PIXI.Texture): PIXI.GetPixelsOutput { const resolution = texture.source.resolution; const frame = texture.frame; const width = Math.max(Math.round(frame.width * resolution), 1); const height = Math.max(Math.round(frame.height * resolution), 1); const pixels = new Uint8Array(BYTES_PER_PIXEL * width * height); // @ts-ignore const renderer = this._renderer; const renderTarget = renderer.renderTarget.getRenderTarget(texture); const glRenterTarget = renderer.renderTarget.getGpuRenderTarget( renderTarget ); const gl = renderer.gl; gl.bindFramebuffer( gl.FRAMEBUFFER, glRenterTarget.resolveTargetFramebuffer ); gl.readPixels( Math.round(frame.x * resolution), Math.round(frame.y * resolution), width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels ); if (multiplyAlpha) { PIXI.unpremultiplyAlpha(pixels); } return { pixels: new Uint8ClampedArray(pixels.buffer), width, height }; }, configurable: true, }); };