项目初始化

This commit is contained in:
jerry
2025-01-21 01:46:34 +08:00
parent 364021b042
commit 48153e7761
962 changed files with 172070 additions and 0 deletions

View File

@@ -0,0 +1,111 @@
# SVGAPlayer-Web
## Install
### Add CreateJS library
```html
<script src="https://code.createjs.com/easeljs-0.8.2.min.js"></script>
```
### Prebuild JS
1. Goto [https://github.com/yyued/SVGAPlayer-Web/tree/master/build](https://github.com/yyued/SVGAPlayer-Web/tree/master/build) Download svga.createjs.min.js
2. Add ```<script src="svga.createjs.min.js"></script>``` to xxx.html
### NPM
1. ```npm install svgaplayerweb --save```
2. Add ``` require('svgaplayerweb/build/svga.createjs.min') ``` to ```xxx.js```
### SVGA-Format 1.x support
Both Prebuild & NPM, if you need to support SVGA-Format 1.x, add JSZip script to html.
```html
<script src="http://assets.dwstatic.com/common/lib/??jszip/3.1.3/jszip.min.js,jszip/3.1.3/jszip-utils.min.js" charset="utf-8"></script>
```
## Usage
```js
var displayObject = new SVGA.CreatejsPlayer('./samples/rose_2.0.0.svga');
displayObject.onError(function(err) {
console.error(err)
})
displayObject.setFrame(0, 0, 500, 500)
var stage = new createjs.Stage('CanvasID');
stage.addChild(displayObject);
```
### Replace Animation Images Dynamically
You can replace specific image by yourself, ask your designer tell you the ImageKey.
* The Replacing Image MUST have same WIDTH and HEIGHT as Original.
* setImage operation MUST set BEFORE startAnimation.
```
displayObject.setImage('http://yourserver.com/xxx.png', 'ImageKey');
```
### Add Text on Animation Image Dynamically
You can add text on specific image, ask your designer tell you the ImageKey.
* setText operation MUST set BEFORE startAnimation.
```
displayObject.setText('Hello, World!', 'ImageKey');
```
```
displayObject.setText({
text: 'Hello, World!,
size: "24px",
color: "#ffe0a4",
offset: {x: 0.0, y: 0.0}
}, 'ImageKey'); // customize text styles.
```
## Classes
### CreatejsPlayer
You use SVGA.CreatejsPlayer controls animation play and stop.
#### Properties
* int loops; - Animation loop count, defaults to 0 means infinity loop.
* BOOL clearsAfterStop; - defaults to true, means player will clear all contents after stop.
* string fillMode; - defaults to Forwardoptional Forward / BackwardfillMode = ForwardAnimation will pause on last frame while finishedfillMode = Backward , Animation will pause on first frame.
#### Methods
* constructor (url: string, autoPlay: boolean);
* startAnimation(, reverse: boolean = false); - start animation from zero frame.
* startAnimationWithRange(range: {location: number, length: number}, reverse: boolean = false); - start animation in [location, location+length] frame range.
* pauseAnimation(); - pause animation on current frame.
* stopAnimation(); - stop animation, clear contents while clearsAfterStop === true
* setContentMode(mode: "ScaleToFill" | "AspectFill" | "AspectFit"); - Specific Scale Mode
* setClipsToBounds(clipsToBounds: boolean); - Clips if image render out of box.
* clear(); - force clear contents.
* stepToFrame(frame: int, andPlay: Boolean); - stop to specific frame, play animation while andPlay === true
* stepToPercentage(percentage: float, andPlay: Boolean); - stop to specific percentage, play animation while andPlay === true
* setImage(image: string, forKey: string, transform: [a, b, c, d, tx, ty]); - Replace Animation Images Dynamically, transform is optional, transform could adjust replacing image.
* setText(text: string | {text: string, font: string, size: string, color: string, offset: {x: float, y: float}}, forKey: string); - Add Text on Animation Image Dynamically
* clearDynamicObjects(); - clear all dynamic objects.
#### Callback Method
* onError(callback: (error: Error) => void): void; - call after load failure.
* onFinished(callback: () => void): void; - call after animation stop.
* onFrame(callback: (frame: number): void): void; - call after animation specific frame rendered.
* onPercentage(callback: (percentage: number): void): void; - call after animation specific percentage rendered.
## Issues
### Android 4.x Breaks
As known, some Android OS lack Blob support, add Blob Polyfill by yourself.
```
<script src="//cdn.bootcss.com/blob-polyfill/1.0.20150320/Blob.min.js"></script>
```

View File

@@ -0,0 +1,25 @@
## Attention
* Do not ask any usage question, issue board is a issue board, accept library bugs only.
* If you are facing any usage problem, read the README again.
## Issue Template
Issue Description(What's your problem)
How To Reappear(How to reappear the issue)
Any Attachment(Provide a sample about your issue)
------ 中文分割线 ------
## 注意
* 不要在 Issue 板块提问使用问题Issue 板块只接受 Bug 反馈。
* 如果遇到使用上的问题,仔细阅读 README。
## Issue 模板
请尽量使用英文提交 Issue
请确切回答:问题的描述、重现方式、附件(提供一个 Demo 以重现问题)

201
uni_modules/c-svga/node_modules/svgaplayerweb/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2016 YY Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,93 @@
# SVGAPlayer-Web
## Install
### Patch laya.webgl.js library
1. Goto [https://github.com/yyued/SVGAPlayer-Web/tree/master/patch/layabox](https://github.com/yyued/SVGAPlayer-Web/tree/master/patch/layabox) Download laya.webgl.js
2. Replace to {LayaProjectDir}/bin/libs/laya.webgl.js
### Prebuild JS
1. Goto [https://github.com/yyued/SVGAPlayer-Web/tree/master/build](https://github.com/yyued/SVGAPlayer-Web/tree/master/build) Download svga.layabox.min.js
2. Add ```<script src="svga.layabox.min.js"></script>``` to index.html
3. Optional add ```index.d.ts``` to your project.
### SVGA-Format 1.x support
If you need to support SVGA-Format 1.x, add JSZip script to html.
```html
<script src="http://assets.dwstatic.com/common/lib/??jszip/3.1.3/jszip.min.js,jszip/3.1.3/jszip-utils.min.js" charset="utf-8"></script>
```
## Usage
```js
const displayObject = new SVGA.LayaboxPlayer('res/svga/rose_2.0.0.svga')
displayObject.setFrame(0, 0, 750, 750);
Laya.stage.addChild(displayObject as any)
```
### Replace Animation Images Dynamically
You can replace specific image by yourself, ask your designer tell you the ImageKey.
* The Replacing Image MUST have same WIDTH and HEIGHT as Original.
* setImage operation MUST set BEFORE startAnimation.
```
displayObject.setImage('http://yourserver.com/xxx.png', 'ImageKey');
```
### Add Text on Animation Image Dynamically
You can add text on specific image, ask your designer tell you the ImageKey.
* setText operation MUST set BEFORE startAnimation.
```
displayObject.setText('Hello, World!', 'ImageKey');
```
```
displayObject.setText({
text: 'Hello, World!,
size: "24px",
color: "#ffe0a4",
offset: {x: 0.0, y: 0.0}
}, 'ImageKey'); // customize text styles.
```
## Classes
### Player
You use SVGA.Player controls animation play and stop.
#### Properties
* int loops; - Animation loop count, defaults to 0 means infinity loop.
* BOOL clearsAfterStop; - defaults to true, means player will clear all contents after stop.
* string fillMode; - defaults to Forwardoptional Forward / BackwardfillMode = ForwardAnimation will pause on last frame while finishedfillMode = Backward , Animation will pause on first frame.
#### Methods
* constructor (url: string, autoPlay: boolean); - first params could be '#id' or CanvasHTMLElement
* startAnimation(reverse: boolean); - start animation from zero frame.
* startAnimationWithRange(range: {location: number, length: number}, reverse: boolean = false); - start animation in [location, location+length] frame range.
* pauseAnimation(); - pause animation on current frame.
* stopAnimation(); - stop animation, clear contents while clearsAfterStop === true
* setContentMode(mode: "ScaleToFill" | "AspectFill" | "AspectFit"); - Specific Scale Mode
* setClipsToBounds(clipsToBounds: boolean); - Clips if image render out of box.
* clear(); - force clear contents.
* stepToFrame(frame: int, andPlay: Boolean); - stop to specific frame, play animation while andPlay === true
* stepToPercentage(percentage: float, andPlay: Boolean); - stop to specific percentage, play animation while andPlay === true
* setImage(image: string, forKey: string, transform: [a, b, c, d, tx, ty]); - Replace Animation Images Dynamically, transform is optional, transform could adjust replacing image.
* setText(text: string | {text: string, font: string, size: string, color: string, offset: {x: float, y: float}}, forKey: string); - Add Text on Animation Image Dynamically
* clearDynamicObjects(); - clear all dynamic objects.
#### Callback Method
* onError(callback: (error: Error) => void): void; - call after load failure.
* onFinished(callback: () => void): void; - call after animation stop.
* onFrame(callback: (frame: number): void): void; - call after animation specific frame rendered.
* onPercentage(callback: (percentage: number): void): void; - call after animation specific percentage rendered.

184
uni_modules/c-svga/node_modules/svgaplayerweb/README.md generated vendored Normal file
View File

@@ -0,0 +1,184 @@
# SVGAPlayer-Web
Language: [中文](README.zh.md)
SVGAPlayer 现已支持在微信小程序播放动画,详情请[参阅](https://github.com/yyued/SVGAPlayer-Web/tree/mp)。
## News
* **[Lite Version](https://github.com/svga/SVGAPlayer-Web-Lite)**
* 2.3.0 - Add audio support.
## Can I Use
SVGAPlayer 2.0.0 only supports below browsers.
* Edge / IE 6+
* Safari / Chrome
* iOS 6.0+ / Android 4.0+
SVGAPlayer 2.0.0 also supports below Game Engines.
* CreateJS [Usage](CreateJS.README.md)
* LayaBox [Usage](LayaBox.README.md)
## Install
### Prebuild JS
1. Add ```<script src="https://cdn.jsdelivr.net/npm/svgaplayerweb@2.3.1/build/svga.min.js"></script>``` to your.html
### NPM
1. ```npm install svgaplayerweb --save```
2. Add ``` require('svgaplayerweb') ``` to ```xxx.js```
### IE6 ~ IE9
* IE6+ only supports 2.x format.
* You couldn't use npm to install SVGA library.
1. Add [SVGAPlayerWeb.swf](https://github.com/yyued/SVGAPlayer-Web/blob/master/tests/SVGAPlayerWeb.swf) to your.html locate directory.
2. Add following code to your.html
```
<!--[if lt IE 10]>
<script src="../build/svga.ie.min.js"></script>
<![endif]-->
<!--[if gte IE 10]><!-->
<script src="../build/svga.min.js"></script>
<!--<![endif]-->
```
### Audio support
If your need to play audios, add ```howler.min.js``` to your html.
```html
<script src="https://cdn.jsdelivr.net/npm/howler@2.0.15/dist/howler.core.min.js"></script>
```
Notice: audio plays needs browser support, some browser requires user interaction before playing.
### SVGA-Format 1.x support
Both Prebuild & NPM, if you need to support SVGA-Format 1.x, add JSZip script to html.
```html
<script src="//s1.yy.com/ued_web_static/lib/jszip/3.1.4/??jszip.min.js,jszip-utils.min.js" charset="utf-8"></script>
```
## Usage
### Load Animation Mannally
You may create Player and Parser by yourself.
1. Add Div Tag.
```html
<div id="demoCanvas" style="styles..."></div>
```
2. Load Animation
```js
var player = new SVGA.Player('#demoCanvas');
var parser = new SVGA.Parser('#demoCanvas'); // Must Provide same selector eg:#demoCanvas IF support IE6+
parser.load('rose_2.0.0.svga', function(videoItem) {
player.setVideoItem(videoItem);
player.startAnimation();
})
```
### Load Animation Automatically
Assign canvas element properties as below.
```html
<div src="rose_2.0.0.svga" loops="0" clearsAfterStop="true" style="styles..."></div>
```
Animation will play after Web-Page onload.
### Replace Animation Images Dynamically
You can replace specific image by yourself, ask your designer tell you the ImageKey.
```
player.setImage('http://yourserver.com/xxx.png', 'ImageKey');
```
### Add Text on Animation Image Dynamically
You can add text on specific image, ask your designer tell you the ImageKey.
```
player.setText('Hello, World!', 'ImageKey');
```
```
player.setText({
text: 'Hello, World!',
family: 'Arial',
size: "24px",
color: "#ffe0a4",
offset: {x: 0.0, y: 0.0}
}, 'ImageKey'); // customize text styles.
```
## Classes
### SVGA.Player
You use SVGA.Player controls animation play and stop.
#### Properties
* int loops; - Animation loop count, defaults to 0 means infinity loop.
* BOOL clearsAfterStop; - defaults to true, means player will clear all contents after stop.
* string fillMode; - defaults to Forwardoptional Forward / BackwardfillMode = ForwardAnimation will pause on last frame while finishedfillMode = Backward , Animation will pause on first frame.
#### Methods
* constructor (canvas); - first params could be '#id' or CanvasHTMLElement
* startAnimation(reverse: boolean = false); - start animation from zero frame.
* startAnimationWithRange(range: {location: number, length: number}, reverse: boolean = false); - start animation in [location, location+length] frame range.
* pauseAnimation(); - pause animation on current frame.
* stopAnimation(); - stop animation, clear contents while clearsAfterStop === true
* setContentMode(mode: "Fill" | "AspectFill" | "AspectFit"); - Specific Scale Mode
* setClipsToBounds(clipsToBounds: boolean); - Clips if image render out of box.
* clear(); - force clear contents.
* stepToFrame(frame: int, andPlay: Boolean); - stop to specific frame, play animation while andPlay === true
* stepToPercentage(percentage: float, andPlay: Boolean); - stop to specific percentage, play animation while andPlay === true
* setImage(image: string, forKey: string, transform: [a, b, c, d, tx, ty]); - Replace Animation Images Dynamically, transform is optional, transform could adjust replacing image.
* setText(text: string | {text: string, family: string, size: string, color: string, offset: {x: float, y: float}}, forKey: string); - Add Text on Animation Image Dynamically
* clearDynamicObjects(); - clear all dynamic objects.
#### Callback Method
* onFinished(callback: () => void): void; - call after animation stop.
* onFrame(callback: (frame: number): void): void; - call after animation specific frame rendered.
* onPercentage(callback: (percentage: number): void): void; - call after animation specific percentage rendered.
### SVGA.Parser
You use SVGA.Parser load VideoItem from remote or Base64 string.
Only Cross-Domain allow files could be loaded.
If you eager to load resources from Base64 or File, deliver as ```load(File)``` or ```load('data:svga/2.0;base64,xxxxxx')```.
#### Methods
* constructor();
* load(url: string, success: (videoItem: VideoEntity) => void, failure: (error: Error) => void): void;
## Issues
### Android 4.x Breaks
As known, some Android OS lack Blob support, add Blob Polyfill by yourself.
```
<script src="//cdn.bootcss.com/blob-polyfill/1.0.20150320/Blob.min.js"></script>
```

View File

@@ -0,0 +1,189 @@
# SVGAPlayer-Web
Language: [English](README.md)
## 版本更新
* **[Lite 版本](https://github.com/svga/SVGAPlayer-Web-Lite)**
* 2.3.0 - 新增音频播放支持
## Can I Use
SVGAPlayer 2.0.0 只支持以下浏览器使用
* Edge / IE 6+
* Safari / Chrome
* iOS 6.0+ / Android 4.0+
SVGAPlayer 2.0.0 同时支持以下游戏引擎使用
* CreateJS [使用指南](CreateJS.README.md)
* LayaBox [使用指南](LayaBox.README.md)
## 安装
### 预编译 JS
1. 添加 ```<script src="https://cdn.jsdelivr.net/npm/svgaplayerweb@2.3.1/build/svga.min.js"></script>``` 到 your.html 页面
### NPM
1. ```npm install svgaplayerweb --save```
2. 添加 ```const SVGA = require('svgaplayerweb'); ``` 或 ```import SVGA from 'svgaplayerweb';``` 至 ```xxx.js```
### IE6 ~ IE9
* IE6+ 只支持 2.x 格式文件.
* 你不能使用 NPM 方式安装 SVGAPlayer.
1. 添加 [SVGAPlayerWeb.swf](https://github.com/yyued/SVGAPlayer-Web/blob/master/tests/SVGAPlayerWeb.swf) 到 your.html 同级目录
2. 添加以下代码至 your.html
```
<!--[if lt IE 10]>
<script src="../build/svga.ie.min.js"></script>
<![endif]-->
<!--[if gte IE 10]><!-->
<script src="../build/svga.min.js"></script>
<!--<![endif]-->
```
### 支持音频播放
如果你需要播放 svga 文件内的音频,请将 ```howler.min.js``` 添加到 HTML 页面中。
```html
<script src="https://cdn.jsdelivr.net/npm/howler@2.0.15/dist/howler.core.min.js"></script>
```
注意:部分浏览器要求在触摸事件发生后才能播放音频。
### 支持 SVGA-Format 1.x 格式
无论是使用预编译 JS 或是 NPM 如果你需要播放 1.x 格式的 SVGA 文件,需要添加 JSZip 到你的 HTML 页面中。
```html
<script src="//s1.yy.com/ued_web_static/lib/jszip/3.1.4/??jszip.min.js,jszip-utils.min.js" charset="utf-8"></script>
```
## 使用指南
### 手动加载
你可以自行创建 Player 和 Parser 并加载动画
1. 添加 Div 容器
```html
<div id="demoCanvas" style="styles..."></div>
```
2. 加载动画
```js
var player = new SVGA.Player('#demoCanvas');
var parser = new SVGA.Parser('#demoCanvas'); // 如果你需要支持 IE6+,那么必须把同样的选择器传给 Parser。
parser.load('rose_2.0.0.svga', function(videoItem) {
player.setVideoItem(videoItem);
player.startAnimation();
})
```
### 自动加载
为 canvas 元素添加`src`属性
```html
<div src="rose_2.0.0.svga" id="demoCanvas" style="styles..."></div>
```
```js
new SVGA.autoload(document.querySelector('#demoCanvas'))
```
动画会在页面加载完成后播放
### 动态图像
你可以动态替换动画中的指定元素,询问你的动画设计师以获取 ImageKey。
* 用于替换的图片,宽、高必须与原图一致。
* setImage 操作必须在 startAnimation 之前执行。
```
player.setImage('http://yourserver.com/xxx.png', 'ImageKey');
```
### 动态文本
你可以在指定元素上添加文本,询问你的动画设计师以获取 ImageKey。
* setText 操作必须在 startAnimation 之前执行。
```
player.setText('Hello, World!', 'ImageKey');
```
```
player.setText({
text: 'Hello, World!,
family: 'Arial',
size: "24px",
color: "#ffe0a4",
offset: {x: 0.0, y: 0.0}
}, 'ImageKey'); // 可自定义文本样式
```
## Classes
### SVGA.Player
SVGA.Player 用于控制动画的播放和停止
#### Properties
* int loops; - 动画循环次数,默认值为 0表示无限循环。
* BOOL clearsAfterStop; - 默认值为 true表示当动画结束时清空画布。
* string fillMode; - 默认值为 Forward可选值 Forward / Backward当 clearsAfterStop 为 false 时Forward 表示动画会在结束后停留在最后一帧Backward 则会在动画结束后停留在第一帧。
#### Methods
* constructor (canvas); - 传入 #id 或者 CanvasHTMLElement 至第一个参数
* startAnimation(reverse: boolean = false); - 从第 0 帧开始播放动画
* startAnimationWithRange(range: {location: number, length: number}, reverse: boolean = false); - 播放 [location, location+length] 指定区间帧动画
* pauseAnimation(); - 暂停在当前帧
* stopAnimation(); - 停止播放动画,如果 clearsAfterStop === true将会清空画布
* setContentMode(mode: "Fill" | "AspectFill" | "AspectFit"); - 设置动画的拉伸模式
* setClipsToBounds(clipsToBounds: boolean); - 如果超出盒子边界,将会进行裁剪
* clear(); - 强制清空画布
* stepToFrame(frame: int, andPlay: Boolean); - 跳到指定帧,如果 andPlay === true则在指定帧开始播放动画
* stepToPercentage(percentage: float, andPlay: Boolean); - 跳到指定百分比,如果 andPlay === true则在指定百分比开始播放动画
* setImage(image: string, forKey: string, transform: [a, b, c, d, tx, ty]); - 设定动态图像, transform 是可选的, transform 用于变换替换图片
* setText(text: string | {text: string, family: string, size: string, color: string, offset: {x: float, y: float}}, forKey: string); - 设定动态文本
* clearDynamicObjects(); - 清空所有动态图像和文本
#### Callback Method
* onFinished(callback: () => void): void; - 动画停止播放时回调
* onFrame(callback: (frame: number): void): void; - 动画播放至某帧后回调
* onPercentage(callback: (percentage: number): void): void; - 动画播放至某进度后回调
### SVGA.Parser
SVGA.Parser 用于加载远端或 Base64 动画,并转换成 VideoItem。
跨域的 SVGA 资源需要使用 CORS 协议才能加载成功。
如果你需要加载 Base64 资源,或者 File 资源,这样传递就可以了 ```load(File)``` 或 ```load('data:svga/2.0;base64,xxxxxx')```。
#### Methods
* constructor();
* load(url: string, success: (videoItem: VideoEntity) => void, failure: (error: Error) => void): void;
## Issues
### Android 4.x 加载失败
某些 Android 4.x OS 上缺少 Blob 支持,请自行添加 Polyfill。
```
<script src="//cdn.bootcss.com/blob-polyfill/1.0.20150320/Blob.min.js"></script>
```

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,71 @@
export as namespace SVGA;
declare global {
const SVGA: {
VideoEntity: typeof VideoEntity,
Parser: typeof Parser,
Player: typeof Player,
CreatejsPlayer: typeof CreatejsPlayer,
LayaboxPlayer: typeof LayaboxPlayer,
}
}
export class VideoEntity {
videoSize: { width: number, height: number }
FPS: number
frames: number
}
export class Parser {
load(url: string, success: (videoItem: VideoEntity) => void, failure?: (err: Error) => void): void
}
export class Player {
loops: number;
clearsAfterStop: boolean;
fillMode: "Forward" | "Backward"
constructor(canvas: string | HTMLCanvasElement | HTMLDivElement)
setVideoItem(videoItem: VideoEntity): void
setContentMode(contentMode: "Fill" | "AspectFill" | "AspectFit"): void
setClipsToBounds(clipsToBounds: boolean): void
startAnimation(reverse?: boolean): void
startAnimationWithRange(range: {location: number, length: number}, reverse?: boolean): void
pauseAnimation(): void
stopAnimation(clear?: boolean): void
clear(): void
stepToFrame(frame: number, andPlay?: boolean): void
stepToPercentage(percentage: number, andPlay?: boolean): void
setImage(urlORbase64: string, forKey: string, transform?: number[]): void
setText(textORMap: string | {
text: string,
size?: string,
family?: string,
color?: string,
offset?: { x: number, y: number }
}, forKey: string): void
clearDynamicObjects(): void
onFinished(callback: () => void): void
onFrame(callback: (frame: number) => void): void
onPercentage(callback: (percentage: number) => void): void
drawOnContext(ctx: CanvasRenderingContext2D, x: number, y: number, width?: number, height?: number): void
}
export class CreatejsPlayer extends Player {
constructor(url: string, autoplay?: boolean)
onError(callback: (error: Error) => void): void
setFrame(x: number, y: number, width: number, height: number): void
}
export class LayaboxPlayer extends Player {
constructor(url?: string, autoplay?: boolean)
setVideoUrl(url?: string, autoplay?: boolean, success?: (videoItem: VideoEntity) => void, failure?: (error: Error) => void): void;
onError(callback: (error: Error) => void): void
setFrame(x: number, y: number, width: number, height: number): void
}

View File

@@ -0,0 +1,61 @@
{
"_from": "svgaplayerweb@^2.3.2",
"_id": "svgaplayerweb@2.3.2",
"_inBundle": false,
"_integrity": "sha512-QuTvNIgy3W6Mi4h74SczEHUtAwb8m3ax7Ai7xRLUuN6hjJh49RGtWOWq1IuF2I7ECcl0HAYn8FcTn99UDz9UiQ==",
"_location": "/svgaplayerweb",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "svgaplayerweb@^2.3.2",
"name": "svgaplayerweb",
"escapedName": "svgaplayerweb",
"rawSpec": "^2.3.2",
"saveSpec": null,
"fetchSpec": "^2.3.2"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmmirror.com/svgaplayerweb/-/svgaplayerweb-2.3.2.tgz",
"_shasum": "15595b8dcc20cf4de4adc3103970b7cf5ae19a84",
"_spec": "svgaplayerweb@^2.3.2",
"_where": "C:\\Users\\pc\\Documents\\HBuilderProjects\\Sapp\\uni_modules\\c-svga",
"author": {
"name": "YYUED"
},
"bugs": {
"url": "https://github.com/yyued/SVGAPlayer-Web/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Language: [中文](README.zh.md)",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"http-server": "^0.10.0",
"pako": "^1.0.6",
"protobufjs": "^6.8.0",
"uglify-js": "^3.1.2",
"value-animator": "git+https://github.com/yyued/value-animator.git",
"webpack": "^3.6.0"
},
"homepage": "https://github.com/yyued/SVGAPlayer-Web#readme",
"license": "Apache License 2.0",
"main": "./build/svga.min.js",
"name": "svgaplayerweb",
"repository": {
"type": "git",
"url": "git+https://github.com/yyued/SVGAPlayer-Web.git"
},
"scripts": {
"build": "webpack",
"start": "http-server ./ & webpack -w & open http://127.0.0.1:8080/tests/"
},
"types": "index.d.ts",
"version": "2.3.2"
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,41 @@
import { Parser } from '../parser'
import { Player } from './player'
export class AutoLoader {
static sharedParser = new Parser();
static autoload = (element, customParser) => {
if (typeof window === "undefined" || typeof document === "undefined") {
return;
}
let parser = customParser || AutoLoader.sharedParser;
if (element) {
if ((element.tagName === "CANVAS" || element.tagName === "DIV") && element.attributes.src && element.attributes.src.value.indexOf(".svga") === element.attributes.src.value.length - 5) {
let src = element.attributes.src.value;
let player = new Player(element);
parser.load(src, (videoItem) => {
if (element.attributes.loops) {
let loops = parseFloat(element.attributes.loops.value) || 0;
player.loops = loops;
}
if (element.attributes.clearsAfterStop) {
let clearsAfterStop = !(element.attributes.clearsAfterStop.value === "false")
player.clearsAfterStop = clearsAfterStop;
}
player.setVideoItem(videoItem);
player.startAnimation();
});
element.player = player;
}
}
else {
var elements = document.querySelectorAll('[src$=".svga"]');
for (var index = 0; index < elements.length; index++) {
var element = elements[index];
AutoLoader.autoload(element);
}
}
}
}

View File

@@ -0,0 +1,11 @@
import { Parser } from '../parser'
import { Player } from './player'
import { AutoLoader } from './autoLoader'
module.exports = {
Parser,
Player,
autoload: AutoLoader.autoload,
}
AutoLoader.autoload();

View File

@@ -0,0 +1,305 @@
'use strict';
import { Renderer } from './renderer'
const ValueAnimator = require("value-animator")
export class Player {
loops = 0;
clearsAfterStop = true;
fillMode = "Forward";
constructor(container) {
this._container = typeof container === "string" ? document.querySelector(container) : container;
this._asChild = container === undefined
this._init();
}
setVideoItem(videoItem) {
this._currentFrame = 0;
this._videoItem = videoItem;
this._renderer.prepare();
this.clear();
this._update();
}
setContentMode(contentMode) {
this._contentMode = contentMode;
this._update();
}
setClipsToBounds(clipsToBounds) {
if (this._container instanceof HTMLDivElement) {
this._container.style.overflowX = this._container.style.overflowY = clipsToBounds ? "hidden" : undefined;
}
}
startAnimation(reverse) {
this.stopAnimation(false);
this._doStart(undefined, reverse, undefined);
}
startAnimationWithRange(range, reverse) {
this.stopAnimation(false);
this._doStart(range, reverse, undefined)
}
pauseAnimation() {
this.stopAnimation(false);
}
stopAnimation(clear) {
this._forwardAnimating = false
if (this._animator !== undefined) {
this._animator.stop()
}
if (clear === undefined) {
clear = this.clearsAfterStop;
}
if (clear) {
this.clear();
}
}
clear() {
this._renderer.clear();
this._renderer.clearAudios();
}
stepToFrame(frame, andPlay) {
if (frame >= this._videoItem.frames || frame < 0) {
return;
}
this.pauseAnimation();
this._currentFrame = frame;
this._update();
if (andPlay) {
this._doStart(undefined, false, this._currentFrame)
}
}
stepToPercentage(percentage, andPlay) {
let frame = parseInt(percentage * this._videoItem.frames);
if (frame >= this._videoItem.frames && frame > 0) {
frame = this._videoItem.frames - 1;
}
this.stepToFrame(frame, andPlay);
}
setImage(urlORbase64, forKey, transform) {
this._dynamicImage[forKey] = urlORbase64;
if (transform !== undefined && transform instanceof Array && transform.length == 6) {
this._dynamicImageTransform[forKey] = transform;
}
}
setText(textORMap, forKey) {
let text = typeof textORMap === "string" ? textORMap : textORMap.text;
let size = (typeof textORMap === "object" ? textORMap.size : "14px") || "14px";
let family = (typeof textORMap === "object" ? textORMap.family : "Arial") || "Arial";
let color = (typeof textORMap === "object" ? textORMap.color : "#000000") || "#000000";
let offset = (typeof textORMap === "object" ? textORMap.offset : { x: 0.0, y: 0.0 }) || { x: 0.0, y: 0.0 };
this._dynamicText[forKey] = {
text,
style: `${size} ${family}`,
color,
offset,
};
}
clearDynamicObjects() {
this._dynamicImage = {};
this._dynamicImageTransform = {};
this._dynamicText = {};
}
onFinished(callback) {
this._onFinished = callback;
}
onFrame(callback) {
this._onFrame = callback;
}
onPercentage(callback) {
this._onPercentage = callback;
}
drawOnContext(ctx, x, y, width, height) {
if (this._drawingCanvas && this._videoItem) {
ctx.drawImage(this._drawingCanvas, x, y, width || this._videoItem.videoSize.width, height || this._videoItem.videoSize.height);
}
}
/**
* Private methods & properties
*/
_asChild = false;
_container = undefined;
_renderer = undefined;
_animator = undefined;
_drawingCanvas = undefined;
_contentMode = "AspectFit"
_videoItem = undefined;
_forwardAnimating = false;
_currentFrame = 0;
_dynamicImage = {};
_dynamicImageTransform = {};
_dynamicText = {};
_onFinished = undefined;
_onFrame = undefined;
_onPercentage = undefined;
_init() {
if (this._container instanceof HTMLDivElement || this._asChild) {
if (this._container) {
const existedCanvasElements = this._container.querySelectorAll('canvas');
for (let index = 0; index < existedCanvasElements.length; index++) {
let element = existedCanvasElements[index];
if (element !== undefined && element.__isPlayer) {
this._container.removeChild(element);
}
}
}
this._drawingCanvas = document.createElement('canvas');
this._drawingCanvas.__isPlayer = true
this._drawingCanvas.style.backgroundColor = "transparent"
if (this._container) {
this._container.appendChild(this._drawingCanvas);
this._container.style.textAlign = "left";
}
}
this._renderer = new Renderer(this);
}
_doStart(range, reverse, fromFrame) {
this._animator = new ValueAnimator()
if (range !== undefined) {
this._animator.startValue = Math.max(0, range.location)
this._animator.endValue = Math.min(this._videoItem.frames - 1, range.location + range.length)
this._animator.duration = (this._animator.endValue - this._animator.startValue + 1) * (1.0 / this._videoItem.FPS) * 1000
}
else {
this._animator.startValue = 0
this._animator.endValue = this._videoItem.frames - 1
this._animator.duration = this._videoItem.frames * (1.0 / this._videoItem.FPS) * 1000
}
this._animator.loops = this.loops <= 0 ? Infinity : this.loops
this._animator.fillRule = this.fillMode === "Backward" ? 1 : 0
this._animator.onUpdate = (value) => {
if (this._currentFrame === Math.floor(value)) {
return;
}
if (this._forwardAnimating && this._currentFrame > Math.floor(value)) {
this._renderer.clearAudios()
}
this._currentFrame = Math.floor(value)
this._update()
if (typeof this._onFrame === "function") {
this._onFrame(this._currentFrame);
}
if (typeof this._onPercentage === "function") {
this._onPercentage(parseFloat(this._currentFrame + 1) / parseFloat(this._videoItem.frames));
}
}
this._animator.onEnd = () => {
this._forwardAnimating = false
if (this.clearsAfterStop === true) {
this.clear()
}
if (typeof this._onFinished === "function") {
this._onFinished();
}
}
if (reverse === true) {
this._animator.reverse(fromFrame)
this._forwardAnimating = false
}
else {
this._animator.start(fromFrame)
this._forwardAnimating = true
}
this._currentFrame = this._animator.startValue
this._update()
}
_resize() {
let asParent = false;
if (this._drawingCanvas) {
let scaleX = 1.0; let scaleY = 1.0; let translateX = 0.0; let translateY = 0.0;
let targetSize;
if (this._drawingCanvas.parentNode) {
targetSize = { width: this._drawingCanvas.parentNode.clientWidth, height: this._drawingCanvas.parentNode.clientHeight };
}
else {
targetSize = this._videoItem.videoSize;
}
let imageSize = this._videoItem.videoSize;
if (targetSize.width >= imageSize.width && targetSize.height >= imageSize.height) {
this._drawingCanvas.width = targetSize.width;
this._drawingCanvas.height = targetSize.height;
this._drawingCanvas.style.webkitTransform = this._drawingCanvas.style.transform = "";
asParent = true;
}
else {
this._drawingCanvas.width = imageSize.width;
this._drawingCanvas.height = imageSize.height;
if (this._contentMode === "Fill") {
const scaleX = targetSize.width / imageSize.width;
const scaleY = targetSize.height / imageSize.height;
const translateX = (imageSize.width * scaleX - imageSize.width) / 2.0
const translateY = (imageSize.height * scaleY - imageSize.height) / 2.0
this._drawingCanvas.style.webkitTransform = this._drawingCanvas.style.transform = "matrix(" + scaleX + ", 0.0, 0.0, " + scaleY + ", " + translateX + ", " + translateY + ")"
}
else if (this._contentMode === "AspectFit" || this._contentMode === "AspectFill") {
const imageRatio = imageSize.width / imageSize.height;
const viewRatio = targetSize.width / targetSize.height;
if ((imageRatio >= viewRatio && this._contentMode === "AspectFit") || (imageRatio <= viewRatio && this._contentMode === "AspectFill")) {
const scale = targetSize.width / imageSize.width;
const translateX = (imageSize.width * scale - imageSize.width) / 2.0
const translateY = (imageSize.height * scale - imageSize.height) / 2.0 + (targetSize.height - imageSize.height * scale) / 2.0
this._drawingCanvas.style.webkitTransform = this._drawingCanvas.style.transform = "matrix(" + scale + ", 0.0, 0.0, " + scale + ", " + translateX + ", " + translateY + ")"
}
else if ((imageRatio < viewRatio && this._contentMode === "AspectFit") || (imageRatio > viewRatio && this._contentMode === "AspectFill")) {
const scale = targetSize.height / imageSize.height;
const translateX = (imageSize.width * scale - imageSize.width) / 2.0 + (targetSize.width - imageSize.width * scale) / 2.0
const translateY = (imageSize.height * scale - imageSize.height) / 2.0
this._drawingCanvas.style.webkitTransform = this._drawingCanvas.style.transform = "matrix(" + scale + ", 0.0, 0.0, " + scale + ", " + translateX + ", " + translateY + ")"
}
}
this._globalTransform = undefined;
}
}
if (this._drawingCanvas === undefined || asParent === true) {
let scaleX = 1.0; let scaleY = 1.0; let translateX = 0.0; let translateY = 0.0;
let targetSize = { width: this._container !== undefined ? this._container.clientWidth : 0.0, height: this._container !== undefined ? this._container.clientHeight : 0.0 };
let imageSize = this._videoItem.videoSize;
if (this._contentMode === "Fill") {
scaleX = targetSize.width / imageSize.width;
scaleY = targetSize.height / imageSize.height;
}
else if (this._contentMode === "AspectFit" || this._contentMode === "AspectFill") {
const imageRatio = imageSize.width / imageSize.height;
const viewRatio = targetSize.width / targetSize.height;
if ((imageRatio >= viewRatio && this._contentMode === "AspectFit") || (imageRatio <= viewRatio && this._contentMode === "AspectFill")) {
scaleX = scaleY = targetSize.width / imageSize.width;
translateY = (targetSize.height - imageSize.height * scaleY) / 2.0
}
else if ((imageRatio < viewRatio && this._contentMode === "AspectFit") || (imageRatio > viewRatio && this._contentMode === "AspectFill")) {
scaleX = scaleY = targetSize.height / imageSize.height;
translateX = (targetSize.width - imageSize.width * scaleX) / 2.0
}
}
this._globalTransform = { a: scaleX, b: 0.0, c: 0.0, d: scaleY, tx: translateX, ty: translateY };
}
}
_update() {
if (this._videoItem === undefined) { return; }
this._resize();
this._renderer.drawFrame(this._currentFrame);
this._renderer.playAudio(this._currentFrame);
}
}

View File

@@ -0,0 +1,504 @@
import { BezierPath } from '../bezierPath'
import { EllipsePath } from '../ellipsePath'
import { RectPath } from '../rectPath'
const validMethods = 'MLHVCSQRZmlhvcsqrz'
export class Renderer {
_owner = undefined;
_prepared = false;
_undrawFrame = undefined;
_bitmapCache = undefined;
_soundsQueue = [];
constructor(owner) {
this._owner = owner;
}
dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
prepare() {
this._prepared = false;
this._bitmapCache = undefined;
if (this._owner._videoItem.images === undefined || Object.keys(this._owner._videoItem.images).length == 0) {
this._bitmapCache = {};
this._prepared = true;
return;
}
if (this._bitmapCache === undefined) {
this._bitmapCache = {};
let totalCount = 0
let loadedCount = 0
for (var imageKey in this._owner._videoItem.images) {
let src = this._owner._videoItem.images[imageKey];
if (src.indexOf("iVBO") === 0 || src.indexOf("/9j/2w") === 0) {
totalCount++;
let imgTag = document.createElement('img');
imgTag.onload = function () {
loadedCount++;
if (loadedCount == totalCount) {
this._prepared = true;
if (typeof this._undrawFrame === "number") {
this.drawFrame(this._undrawFrame);
this._undrawFrame = undefined;
}
}
}.bind(this);
imgTag.src = 'data:image/png;base64,' + src;
let bitmapKey = imageKey.replace(".matte", "");
this._bitmapCache[bitmapKey] = imgTag;
}
else if (src.indexOf("SUQz") === 0) {
if (window.Howl !== undefined) {
totalCount++;
var sound = new Howl({
src: [(navigator.vendor === "Google Inc." ? URL.createObjectURL(this.dataURLtoBlob('data:audio/x-mpeg;base64,' + src)) : 'data:audio/x-mpeg;base64,' + src)],
html5: navigator.vendor === "Google Inc." ? true : undefined,
preload: navigator.vendor === "Google Inc." ? true : undefined,
format: navigator.vendor === "Google Inc." ? ["mp3"] : undefined,
});
sound.once("load", function () {
loadedCount++;
if (loadedCount == totalCount) {
this._prepared = true;
if (typeof this._undrawFrame === "number") {
this.drawFrame(this._undrawFrame);
this._undrawFrame = undefined;
}
}
}.bind(this))
sound.on("loaderror", function (e) {
console.error(e)
})
this._bitmapCache[imageKey] = sound;
}
}
}
}
}
clear() {
const ctx = (this._owner._drawingCanvas || this._owner._container).getContext('2d')
const areaFrame = {
x: 0.0,
y: 0.0,
width: (this._owner._drawingCanvas || this._owner._container).width,
height: (this._owner._drawingCanvas || this._owner._container).height,
}
ctx.clearRect(areaFrame.x, areaFrame.y, areaFrame.width, areaFrame.height)
}
clearAudios() {
this._soundsQueue.forEach(it => {
it.player.stop(it.playID)
})
this._soundsQueue = []
}
drawFrame(frame) {
if (this._prepared) {
const ctx = (this._owner._drawingCanvas || this._owner._container).getContext('2d')
const areaFrame = {
x: 0.0,
y: 0.0,
width: (this._owner._drawingCanvas || this._owner._container).width,
height: (this._owner._drawingCanvas || this._owner._container).height,
}
ctx.clearRect(areaFrame.x, areaFrame.y, areaFrame.width, areaFrame.height)
var matteSprites = new Map();
var isMatteing = false;
var sprites = this._owner._videoItem.sprites;
sprites.forEach((sprite, index) => {
if (sprites[0].imageKey.indexOf(".matte") == -1) {
this.drawSprite(sprite, ctx, frame);
return;
}
if (sprite.imageKey.indexOf(".matte") != -1) {
matteSprites.set(sprite.imageKey, sprite);
return;
}
var lastSprite = sprites[index - 1];
if (isMatteing && ((sprite.matteKey == null || sprite.matteKey.length == 0) || sprite.matteKey != lastSprite.matteKey)) {
isMatteing = false;
var matteSprite = matteSprites.get(sprite.matteKey);
ctx.globalCompositeOperation = "destination-in";
this.drawSprite(matteSprite, ctx, frame);
ctx.globalCompositeOperation = "source-over";
ctx.restore();
}
if (sprite.matteKey != null && ((lastSprite.matteKey == null || lastSprite.matteKey.length == 0) || lastSprite.matteKey != sprite.matteKey)) {
isMatteing = true;
ctx.save();
}
this.drawSprite(sprite, ctx, frame);
if (isMatteing && index == sprites.length - 1) {
var matteSprite = matteSprites.get(sprite.matteKey);
ctx.globalCompositeOperation = "destination-in";
this.drawSprite(matteSprite, ctx, frame);
ctx.globalCompositeOperation = "source-over";
ctx.restore();
}
});
}
else {
this._undrawFrame = frame;
}
}
drawSprite(sprite, ctx, frameIndex) {
let frameItem = sprite.frames[this._owner._currentFrame];
if (frameItem.alpha < 0.05) {
return;
}
ctx.save();
if (this._owner._globalTransform) {
ctx.transform(this._owner._globalTransform.a, this._owner._globalTransform.b, this._owner._globalTransform.c, this._owner._globalTransform.d, this._owner._globalTransform.tx, this._owner._globalTransform.ty)
}
ctx.globalAlpha = frameItem.alpha;
ctx.transform(frameItem.transform.a, frameItem.transform.b, frameItem.transform.c, frameItem.transform.d, frameItem.transform.tx, frameItem.transform.ty)
let bitmapKey = sprite.imageKey.replace(".matte", "");
let src = this._owner._dynamicImage[bitmapKey] || this._bitmapCache[bitmapKey] || this._owner._videoItem.images[bitmapKey];
if (typeof src === "string") {
let imgTag = this._bitmapCache[sprite.imageKey] || document.createElement('img');
let targetWidth = undefined;
let targetHeight = undefined;
if (src.indexOf("iVBO") === 0 || src.indexOf("/9j/2w") === 0) {
imgTag.src = 'data:image/png;base64,' + src;
}
else {
if (imgTag._svgaSrc !== src) {
imgTag._svgaSrc = src;
imgTag.src = src;
}
targetWidth = frameItem.layout.width;
targetHeight = frameItem.layout.height;
}
this._bitmapCache[sprite.imageKey] = imgTag;
if (frameItem.maskPath !== undefined && frameItem.maskPath !== null) {
this.drawBezier(ctx, frameItem.maskPath);
ctx.clip();
}
if (this._owner._dynamicImageTransform[sprite.imageKey] !== undefined) {
ctx.save();
const concatTransform = this._owner._dynamicImageTransform[sprite.imageKey];
ctx.transform(concatTransform[0], concatTransform[1], concatTransform[2], concatTransform[3], concatTransform[4], concatTransform[5]);
}
if (targetWidth && targetHeight) { ctx.drawImage(imgTag, 0, 0, targetWidth, targetHeight); }
else { ctx.drawImage(imgTag, 0, 0); }
if (this._owner._dynamicImageTransform[sprite.imageKey] !== undefined) {
ctx.restore();
}
}
else if (typeof src === "object") {
if (frameItem.maskPath !== undefined && frameItem.maskPath !== null) {
frameItem.maskPath._styles = undefined;
this.drawBezier(ctx, frameItem.maskPath);
ctx.clip();
}
if (this._owner._dynamicImageTransform[sprite.imageKey] !== undefined) {
ctx.save();
const concatTransform = this._owner._dynamicImageTransform[sprite.imageKey];
ctx.transform(concatTransform[0], concatTransform[1], concatTransform[2], concatTransform[3], concatTransform[4], concatTransform[5]);
}
ctx.drawImage(src, 0, 0);
if (this._owner._dynamicImageTransform[sprite.imageKey] !== undefined) {
ctx.restore();
}
}
frameItem.shapes && frameItem.shapes.forEach(shape => {
if (shape.type === "shape" && shape.pathArgs && shape.pathArgs.d) {
this.drawBezier(ctx, new BezierPath(shape.pathArgs.d, shape.transform, shape.styles))
}
if (shape.type === "ellipse" && shape.pathArgs) {
this.drawEllipse(ctx, new EllipsePath(parseFloat(shape.pathArgs.x) || 0.0, parseFloat(shape.pathArgs.y) || 0.0, parseFloat(shape.pathArgs.radiusX) || 0.0, parseFloat(shape.pathArgs.radiusY) || 0.0, shape.transform, shape.styles))
}
if (shape.type === "rect" && shape.pathArgs) {
this.drawRect(ctx, new RectPath(parseFloat(shape.pathArgs.x) || 0.0, parseFloat(shape.pathArgs.y) || 0.0, parseFloat(shape.pathArgs.width) || 0.0, parseFloat(shape.pathArgs.height) || 0.0, parseFloat(shape.pathArgs.cornerRadius) || 0.0, shape.transform, shape.styles))
}
})
let dynamicText = this._owner._dynamicText[sprite.imageKey];
if (dynamicText !== undefined) {
ctx.textBaseline = "middle";
ctx.font = dynamicText.style;
let textWidth = ctx.measureText(dynamicText.text).width
ctx.fillStyle = dynamicText.color;
let offsetX = (dynamicText.offset !== undefined && dynamicText.offset.x !== undefined) ? isNaN(parseFloat(dynamicText.offset.x)) ? 0 : parseFloat(dynamicText.offset.x) : 0;
let offsetY = (dynamicText.offset !== undefined && dynamicText.offset.y !== undefined) ? isNaN(parseFloat(dynamicText.offset.y)) ? 0 : parseFloat(dynamicText.offset.y) : 0;
ctx.fillText(dynamicText.text, (frameItem.layout.width - textWidth) / 2 + offsetX, frameItem.layout.height / 2 + offsetY);
}
ctx.restore();
}
playAudio(frame) {
if (this._owner._forwardAnimating && this._owner._videoItem.audios instanceof Array) {
this._owner._videoItem.audios.forEach(audio => {
if (audio.startFrame === frame && this._bitmapCache[audio.audioKey] !== undefined && typeof this._bitmapCache[audio.audioKey].play === "function") {
const item = {
playID: this._bitmapCache[audio.audioKey].play(),
player: this._bitmapCache[audio.audioKey],
endFrame: audio.endFrame,
}
item.player.seek(audio.startTime / 1000, item.playID)
this._soundsQueue.push(item)
}
})
let deleted = false
this._soundsQueue.forEach(it => {
if (frame >= it.endFrame) {
deleted = true
it.player.stop(it.playID)
}
})
if (deleted) {
this._soundsQueue = this._soundsQueue.filter(it => frame < it.endFrame)
}
}
}
resetShapeStyles(ctx, obj) {
const styles = obj._styles;
if (styles === undefined) { return; }
if (styles && styles.stroke) {
ctx.strokeStyle = `rgba(${parseInt(styles.stroke[0] * 255)}, ${parseInt(styles.stroke[1] * 255)}, ${parseInt(styles.stroke[2] * 255)}, ${styles.stroke[3]})`;
}
else {
ctx.strokeStyle = "transparent"
}
if (styles) {
ctx.lineWidth = styles.strokeWidth || undefined;
ctx.lineCap = styles.lineCap || undefined;
ctx.lineJoin = styles.lineJoin || undefined;
ctx.miterLimit = styles.miterLimit || undefined;
}
if (styles && styles.fill) {
ctx.fillStyle = `rgba(${parseInt(styles.fill[0] * 255)}, ${parseInt(styles.fill[1] * 255)}, ${parseInt(styles.fill[2] * 255)}, ${styles.fill[3]})`
}
else {
ctx.fillStyle = "transparent"
}
if (styles && styles.lineDash) {
ctx.setLineDash(styles.lineDash);
}
}
drawBezier(ctx, obj) {
ctx.save();
this.resetShapeStyles(ctx, obj);
if (obj._transform !== undefined && obj._transform !== null) {
ctx.transform(obj._transform.a, obj._transform.b, obj._transform.c, obj._transform.d, obj._transform.tx, obj._transform.ty);
}
let currentPoint = { x: 0, y: 0, x1: 0, y1: 0, x2: 0, y2: 0 }
ctx.beginPath();
const d = obj._d.replace(/([a-zA-Z])/g, '|||$1 ').replace(/,/g, ' ');
d.split('|||').forEach(segment => {
if (segment.length == 0) { return; }
const firstLetter = segment.substr(0, 1);
if (validMethods.indexOf(firstLetter) >= 0) {
const args = segment.substr(1).trim().split(" ");
this.drawBezierElement(ctx, currentPoint, firstLetter, args);
}
})
if (obj._styles && obj._styles.fill) {
ctx.fill();
}
if (obj._styles && obj._styles.stroke) {
ctx.stroke();
}
ctx.restore();
}
drawBezierElement(ctx, currentPoint, method, args) {
switch (method) {
case 'M':
currentPoint.x = Number(args[0]);
currentPoint.y = Number(args[1]);
ctx.moveTo(currentPoint.x, currentPoint.y);
break;
case 'm':
currentPoint.x += Number(args[0]);
currentPoint.y += Number(args[1]);
ctx.moveTo(currentPoint.x, currentPoint.y);
break;
case 'L':
currentPoint.x = Number(args[0]);
currentPoint.y = Number(args[1]);
ctx.lineTo(currentPoint.x, currentPoint.y);
break;
case 'l':
currentPoint.x += Number(args[0]);
currentPoint.y += Number(args[1]);
ctx.lineTo(currentPoint.x, currentPoint.y);
break;
case 'H':
currentPoint.x = Number(args[0]);
ctx.lineTo(currentPoint.x, currentPoint.y);
break;
case 'h':
currentPoint.x += Number(args[0]);
ctx.lineTo(currentPoint.x, currentPoint.y);
break;
case 'V':
currentPoint.y = Number(args[0]);
ctx.lineTo(currentPoint.x, currentPoint.y);
break;
case 'v':
currentPoint.y += Number(args[0]);
ctx.lineTo(currentPoint.x, currentPoint.y);
break;
case 'C':
currentPoint.x1 = Number(args[0]);
currentPoint.y1 = Number(args[1]);
currentPoint.x2 = Number(args[2]);
currentPoint.y2 = Number(args[3]);
currentPoint.x = Number(args[4]);
currentPoint.y = Number(args[5]);
ctx.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
break;
case 'c':
currentPoint.x1 = currentPoint.x + Number(args[0]);
currentPoint.y1 = currentPoint.y + Number(args[1]);
currentPoint.x2 = currentPoint.x + Number(args[2]);
currentPoint.y2 = currentPoint.y + Number(args[3]);
currentPoint.x += Number(args[4]);
currentPoint.y += Number(args[5]);
ctx.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
break;
case 'S':
if (currentPoint.x1 && currentPoint.y1 && currentPoint.x2 && currentPoint.y2) {
currentPoint.x1 = currentPoint.x - currentPoint.x2 + currentPoint.x;
currentPoint.y1 = currentPoint.y - currentPoint.y2 + currentPoint.y;
currentPoint.x2 = Number(args[0]);
currentPoint.y2 = Number(args[1]);
currentPoint.x = Number(args[2]);
currentPoint.y = Number(args[3]);
ctx.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
} else {
currentPoint.x1 = Number(args[0]);
currentPoint.y1 = Number(args[1]);
currentPoint.x = Number(args[2]);
currentPoint.y = Number(args[3]);
ctx.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
}
break;
case 's':
if (currentPoint.x1 && currentPoint.y1 && currentPoint.x2 && currentPoint.y2) {
currentPoint.x1 = currentPoint.x - currentPoint.x2 + currentPoint.x;
currentPoint.y1 = currentPoint.y - currentPoint.y2 + currentPoint.y;
currentPoint.x2 = currentPoint.x + Number(args[0]);
currentPoint.y2 = currentPoint.y + Number(args[1]);
currentPoint.x += Number(args[2]);
currentPoint.y += Number(args[3]);
ctx.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
} else {
currentPoint.x1 = currentPoint.x + Number(args[0]);
currentPoint.y1 = currentPoint.y + Number(args[1]);
currentPoint.x += Number(args[2]);
currentPoint.y += Number(args[3]);
ctx.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
}
break;
case 'Q':
currentPoint.x1 = Number(args[0]);
currentPoint.y1 = Number(args[1]);
currentPoint.x = Number(args[2]);
currentPoint.y = Number(args[3]);
ctx.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
break;
case 'q':
currentPoint.x1 = currentPoint.x + Number(args[0]);
currentPoint.y1 = currentPoint.y + Number(args[1]);
currentPoint.x += Number(args[2]);
currentPoint.y += Number(args[3]);
ctx.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
break;
case 'A':
break;
case 'a':
break;
case 'Z':
case 'z':
ctx.closePath();
break;
default:
break;
}
}
drawEllipse(ctx, obj) {
ctx.save();
this.resetShapeStyles(ctx, obj);
if (obj._transform !== undefined && obj._transform !== null) {
ctx.transform(obj._transform.a, obj._transform.b, obj._transform.c, obj._transform.d, obj._transform.tx, obj._transform.ty);
}
let x = obj._x - obj._radiusX;
let y = obj._y - obj._radiusY;
let w = obj._radiusX * 2;
let h = obj._radiusY * 2;
var kappa = .5522848,
ox = (w / 2) * kappa,
oy = (h / 2) * kappa,
xe = x + w,
ye = y + h,
xm = x + w / 2,
ym = y + h / 2;
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
if (obj._styles && obj._styles.fill) {
ctx.fill();
}
if (obj._styles && obj._styles.stroke) {
ctx.stroke();
}
ctx.restore();
}
drawRect(ctx, obj) {
ctx.save();
this.resetShapeStyles(ctx, obj);
if (obj._transform !== undefined && obj._transform !== null) {
ctx.transform(obj._transform.a, obj._transform.b, obj._transform.c, obj._transform.d, obj._transform.tx, obj._transform.ty);
}
let x = obj._x;
let y = obj._y;
let width = obj._width;
let height = obj._height;
let radius = obj._cornerRadius;
if (width < 2 * radius) { radius = width / 2; }
if (height < 2 * radius) { radius = height / 2; }
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.arcTo(x + width, y, x + width, y + height, radius);
ctx.arcTo(x + width, y + height, x, y + height, radius);
ctx.arcTo(x, y + height, x, y, radius);
ctx.arcTo(x, y, x + width, y, radius);
ctx.closePath();
if (obj._styles && obj._styles.fill) {
ctx.fill();
}
if (obj._styles && obj._styles.stroke) {
ctx.stroke();
}
ctx.restore();
}
}

View File

@@ -0,0 +1,8 @@
import { Parser } from '../parser'
import { Player } from './player'
module.exports = {
Parser,
Player,
CreatejsPlayer: Player,
}

View File

@@ -0,0 +1,273 @@
import { Renderer } from './renderer'
import { Parser } from '../parser'
const ValueAnimator = require("value-animator")
export class Player extends createjs.Container {
loops = 0;
clearsAfterStop = true;
fillMode = "Forward";
constructor(url, autoplay) {
super();
(new Parser()).load(url, (videoItem) => {
this.setVideoItem(videoItem);
if (autoplay !== false) {
this.startAnimation();
}
}, (error) => {
this._onError && this._onError(error);
})
this._renderer = new Renderer(this);
}
setVideoItem(videoItem) {
this._currentFrame = 0;
this._videoItem = videoItem;
this.removeAllChildren();
this._addLayers();
}
setContentMode(contentMode) {
this._contentMode = contentMode;
this._update();
}
setClipsToBounds(clipsToBounds) {
this._clipsToBounds = clipsToBounds;
this._update();
}
setFrame(x, y, width, height) {
this._frame = { x, y, width, height }
this._update();
}
startAnimation(reverse) {
this.visible = true;
this.stopAnimation(false);
this._doStart(undefined, reverse, undefined);
}
startAnimationWithRange(range, reverse) {
this.visible = true;
this.stopAnimation(false);
this._doStart(range, reverse, undefined)
}
pauseAnimation() {
this.stopAnimation(false);
}
stopAnimation(clear) {
if (this._animator !== undefined) {
this._animator.stop()
}
if (clear === undefined) {
clear = this.clearsAfterStop;
}
if (clear) {
this.clear();
}
}
clear() {
this.visible = false;
if (this.stage != null) {
this.stage.update();
}
}
stepToFrame(frame, andPlay) {
if (frame >= this._videoItem.frames || frame < 0) {
return;
}
this.visible = true;
this.pauseAnimation();
this._currentFrame = frame;
this._update();
if (andPlay) {
this._doStart(undefined, false, this._currentFrame)
}
}
stepToPercentage(percentage, andPlay) {
let frame = parseInt(percentage * this._videoItem.frames);
if (frame >= this._videoItem.frames && frame > 0) {
frame = this._videoItem.frames - 1;
}
this.stepToFrame(frame, andPlay);
}
setImage(urlORbase64, forKey, transform) {
this._dynamicImage[forKey] = urlORbase64;
if (transform !== undefined && transform instanceof Array && transform.length == 6) {
this._dynamicImageTransform[forKey] = transform;
}
if (this._videoItem !== undefined) {
const currentFrame = this._currentFrame;
this.removeAllChildren();
this._addLayers();
this._currentFrame = currentFrame;
this._update();
}
}
setText(textORMap, forKey) {
let text = typeof textORMap === "string" ? textORMap : textORMap.text;
let size = (typeof textORMap === "object" ? textORMap.size : "14px") || "14px";
let family = (typeof textORMap === "object" ? textORMap.family : "Arial") || "Arial";
let color = (typeof textORMap === "object" ? textORMap.color : "#000000") || "#000000";
let offset = (typeof textORMap === "object" ? textORMap.offset : { x: 0.0, y: 0.0 }) || { x: 0.0, y: 0.0 };
let textLayer = new createjs.Text(text, `${size} family`, color);
textLayer.offset = offset;
this._dynamicText[forKey] = textLayer;
if (this._videoItem !== undefined) {
const currentFrame = this._currentFrame;
this.removeAllChildren();
this._addLayers();
this._currentFrame = currentFrame;
this._update();
}
}
clearDynamicObjects() {
this._dynamicImage = {};
this._dynamicImageTransform = {};
this._dynamicText = {};
}
onError(callback) {
this._onError = callback;
}
onFinished(callback) {
this._onFinished = callback;
}
onFrame(callback) {
this._onFrame = callback;
}
onPercentage(callback) {
this._onPercentage = callback;
}
/**
* Private methods & properties
*/
_renderer = undefined;
_animator = undefined;
_contentMode = "AspectFit"
_videoItem = undefined;
_currentFrame = 0;
_dynamicImage = {};
_dynamicImageTransform = {};
_dynamicText = {};
_onFinished = undefined;
_onFrame = undefined;
_onPercentage = undefined;
_clipsToBounds = false;
_frame = { x: 0, y: 0, width: 0, height: 0 };
_doStart(range, reverse, fromFrame) {
this._animator = new ValueAnimator()
if (range !== undefined) {
this._animator.startValue = Math.max(0, range.location)
this._animator.endValue = Math.min(this._videoItem.frames - 1, range.location + range.length)
this._animator.duration = (this._animator.endValue - this._animator.startValue + 1) * (1.0 / this._videoItem.FPS) * 1000
}
else {
this._animator.startValue = 0
this._animator.endValue = this._videoItem.frames - 1
this._animator.duration = this._videoItem.frames * (1.0 / this._videoItem.FPS) * 1000
}
this._animator.loops = this.loops <= 0 ? Infinity : this.loops
this._animator.fillRule = this.fillMode === "Backward" ? 1 : 0
this._animator.onUpdate = (value) => {
if (this._currentFrame === Math.floor(value)) {
return;
}
this._currentFrame = Math.floor(value)
this._update()
if (typeof this._onFrame === "function") {
this._onFrame(this._currentFrame);
}
if (typeof this._onPercentage === "function") {
this._onPercentage(parseFloat(this._currentFrame + 1) / parseFloat(this._videoItem.frames));
}
}
this._animator.onEnd = () => {
if (this.clearsAfterStop === true) {
this.clear()
}
if (typeof this._onFinished === "function") {
this._onFinished();
}
}
if (reverse === true) {
this._animator.reverse(fromFrame)
}
else {
this._animator.start(fromFrame)
}
}
_addLayers() {
this._videoItem.sprites.forEach((sprite) => {
this.addChild(this._renderer.requestContentLayer(sprite));
})
this._currentFrame = 0;
this._update();
}
_resize() {
let scaleX = 1.0; let scaleY = 1.0; let translateX = 0.0; let translateY = 0.0;
let targetSize = { width: this._frame.width, height: this._frame.height };
let imageSize = this._videoItem.videoSize;
if (this._contentMode === "Fill") {
scaleX = targetSize.width / imageSize.width;
scaleY = targetSize.height / imageSize.height;
}
else if (this._contentMode === "AspectFit" || this._contentMode === "AspectFill") {
const imageRatio = imageSize.width / imageSize.height;
const viewRatio = targetSize.width / targetSize.height;
if ((imageRatio >= viewRatio && this._contentMode === "AspectFit") || (imageRatio <= viewRatio && this._contentMode === "AspectFill")) {
scaleX = scaleY = targetSize.width / imageSize.width;
translateY = (targetSize.height - imageSize.height * scaleY) / 2.0
}
else if ((imageRatio < viewRatio && this._contentMode === "AspectFit") || (imageRatio > viewRatio && this._contentMode === "AspectFill")) {
scaleX = scaleY = targetSize.height / imageSize.height;
translateX = (targetSize.width - imageSize.width * scaleX) / 2.0
}
}
this.transformMatrix = { a: scaleX, b: 0.0, c: 0.0, d: scaleY, tx: this._frame.x + translateX, ty: this._frame.y + translateY };
}
_updateMask() {
if (this._clipsToBounds) {
this.mask = new createjs.Shape();
if (this.mask.__width !== this._frame.__width || this.mask.height !== this._frame.height) {
this.mask.graphics.clear();
this.mask.graphics.drawRect(0.0, 0.0, this._frame.width, this._frame.height);
this.mask.__width = this._frame.width;
this.mask.__height = this._frame.height;
}
}
else {
this.mask = undefined;
}
}
_update() {
if (this._videoItem === undefined) { return; }
this._resize();
this._updateMask();
this._renderer.drawFrame(this._currentFrame);
if (this.stage != null) {
this.stage.update();
}
}
}

View File

@@ -0,0 +1,344 @@
import { BezierPath } from '../bezierPath'
import { EllipsePath } from '../ellipsePath'
import { RectPath } from '../rectPath'
const validMethods = 'MLHVCSQRZmlhvcsqrz'
class VectorLayer extends createjs.Container {
_sprite;
_drawedFrame = 0;
_keepFrameCache = {};
constructor(sprite) {
super();
this._sprite = sprite;
this._resetKeepFrameCache();
}
stepToFrame(frame) {
if (frame < this._sprite.frames.length) {
this._drawFrame(frame);
}
}
_resetKeepFrameCache() {
this._keepFrameCache = {}
let lastKeep = 0;
this._sprite.frames.forEach((frameItem, idx) => {
if (!this._isKeepFrame(frameItem)) {
lastKeep = idx;
}
else {
this._keepFrameCache[idx] = lastKeep;
}
});
}
_requestKeepFrame(frame) {
return this._keepFrameCache[frame]
}
_isKeepFrame(frameItem) {
return frameItem.shapes && frameItem.shapes.length > 0 && frameItem.shapes[0].type === "keep";
}
_drawFrame(frame) {
if (frame < this._sprite.frames.length) {
let frameItem = this._sprite.frames[frame];
if (this._isKeepFrame(frameItem)) {
if (this._drawedFrame === this._requestKeepFrame(frame)) {
return;
}
}
this.removeAllChildren();
frameItem.shapes.forEach((shape) => {
if (shape.type === "shape" && shape.pathArgs && shape.pathArgs.d) {
this.addChild(Renderer.requestBezierShape(new BezierPath(shape.pathArgs.d, shape.transform, shape.styles)));
}
else if (shape.type === "ellipse" && shape.pathArgs) {
this.addChild(Renderer.requestEllipseShape(new EllipsePath(parseFloat(shape.pathArgs.x) || 0.0, parseFloat(shape.pathArgs.y) || 0.0, parseFloat(shape.pathArgs.radiusX) || 0.0, parseFloat(shape.pathArgs.radiusY) || 0.0, shape.transform, shape.styles)));
}
else if (shape.type === "rect" && shape.pathArgs) {
this.addChild(Renderer.requestRectShape(new RectPath(parseFloat(shape.pathArgs.x) || 0.0, parseFloat(shape.pathArgs.y) || 0.0, parseFloat(shape.pathArgs.width) || 0.0, parseFloat(shape.pathArgs.height) || 0.0, parseFloat(shape.pathArgs.cornerRadius) || 0.0, shape.transform, shape.styles)));
}
})
this._drawedFrame = frame;
}
}
}
export class Renderer {
_owner;
constructor(owner) {
this._owner = owner;
}
requestContentLayer(sprite) {
let bitmap;
let contentLayer = new createjs.Container();
if (sprite.imageKey) {
bitmap = this._owner._dynamicImage[sprite.imageKey] || this._owner._videoItem.images[sprite.imageKey];
if (bitmap) {
contentLayer.addChild(this.requestBitmapLayer(bitmap, this._owner._dynamicImageTransform[sprite.imageKey], sprite.frames));
}
if (this._owner._dynamicText[sprite.imageKey]) {
contentLayer.textLayer = this._owner._dynamicText[sprite.imageKey];
contentLayer.addChild(this._owner._dynamicText[sprite.imageKey])
}
}
contentLayer.addChild(this.requestVectorLayer(sprite));
contentLayer.stepToFrame = (frame) => {
if (frame < sprite.frames.length) {
let frameItem = sprite.frames[frame];
if (frameItem.alpha > 0.0) {
contentLayer.alpha = frameItem.alpha;
contentLayer.visible = true;
contentLayer.transformMatrix = new window.createjs.Matrix2D(frameItem.transform.a, frameItem.transform.b, frameItem.transform.c, frameItem.transform.d, frameItem.transform.tx, frameItem.transform.ty);
contentLayer.setBounds({ x: frameItem.layout.x, y: frameItem.layout.y, width: frameItem.layout.width, height: frameItem.layout.height });
if (frameItem.maskPath) {
contentLayer.mask = Renderer.requestBezierShape(frameItem.maskPath);
contentLayer.mask.transformMatrix = contentLayer.transformMatrix;
}
else {
contentLayer.mask = undefined;
}
if (contentLayer.textLayer) {
let offsetX = (contentLayer.textLayer.offset !== undefined && contentLayer.textLayer.offset.x !== undefined) ? contentLayer.textLayer.offset.x : 0;
let offsetY = (contentLayer.textLayer.offset !== undefined && contentLayer.textLayer.offset.y !== undefined) ? contentLayer.textLayer.offset.y : 0;
contentLayer.textLayer.textBaseline = "middle";
contentLayer.textLayer.x = (frameItem.layout.width - contentLayer.textLayer.getBounds().width) / 2.0 + offsetX;
contentLayer.textLayer.y = frameItem.layout.height / 2.0 + offsetY;
}
}
else {
contentLayer.visible = false;
}
}
contentLayer.children.forEach((element) => {
element.stepToFrame && element.stepToFrame(frame);
})
}
return contentLayer;
}
requestBitmapLayer(bitmap, bitmapTransform, frames) {
let imgTag = document.createElement('img');
let backCanvas;
if (bitmap.indexOf("iVBO") === 0 || bitmap.indexOf("/9j/2w") === 0) {
imgTag.src = 'data:image/png;base64,' + bitmap;
}
else {
imgTag.src = bitmap;
if (frames[0] && frames[0].layout) {
backCanvas = document.createElement('canvas');
backCanvas.width = frames[0].layout.width
backCanvas.height = frames[0].layout.height
imgTag.onload = function() {
backCanvas.getContext('2d').drawImage(imgTag, 0, 0, frames[0].layout.width, frames[0].layout.height)
}
}
}
let layer = new createjs.Bitmap(backCanvas || imgTag);
if (bitmapTransform !== undefined) {
layer.transformMatrix = new createjs.Matrix2D(bitmapTransform[0], bitmapTransform[1], bitmapTransform[2], bitmapTransform[3], bitmapTransform[4], bitmapTransform[5]);
}
layer.frames = frames;
layer.stepToFrame = (frame) => { }
return layer;
}
requestVectorLayer(sprite) {
return new VectorLayer(sprite);
}
drawFrame(frame) {
this._owner.children.forEach((element) => {
element.stepToFrame(frame);
});
}
static resetStyle(obj, shape) {
const styles = obj._styles;
if (!styles) { return; }
if (styles && styles.stroke) {
shape.graphics.beginStroke(`rgba(${parseInt(styles.stroke[0] * 255)}, ${parseInt(styles.stroke[1] * 255)}, ${parseInt(styles.stroke[2] * 255)}, ${styles.stroke[3]})`);
}
if (styles) {
const width = styles.strokeWidth || 0.0;
const caps = styles.lineCap || '';
const joints = styles.lineJoin || '';
const miterLimit = styles.miterLimit || '';
shape.graphics.setStrokeStyle(width, caps, joints, miterLimit, true);
}
if (styles && styles.fill) {
shape.graphics.beginFill(`rgba(${parseInt(styles.fill[0] * 255)}, ${parseInt(styles.fill[1] * 255)}, ${parseInt(styles.fill[2] * 255)}, ${styles.fill[3]})`);
}
if (styles && styles.lineDash) {
shape.graphics.setStrokeDash([styles.lineDash[0], styles.lineDash[1]], styles.lineDash[2]);
}
}
static requestBezierShape(obj) {
const shape = new createjs.Shape()
const g = shape.graphics;
this.resetStyle(obj, shape);
let currentPoint = { x: 0, y: 0, x1: 0, y1: 0, x2: 0, y2: 0 }
const d = obj._d.replace(/([a-zA-Z])/g, '|||$1 ').replace(/,/g, ' ');
d.split('|||').forEach(segment => {
if (segment.length == 0) { return; }
const firstLetter = segment.substr(0, 1);
if (validMethods.indexOf(firstLetter) >= 0) {
const args = segment.substr(1).trim().split(" ");
this.drawBezierElement(g, currentPoint, firstLetter, args);
}
})
if (obj._transform !== undefined && obj._transform !== null) {
shape.transformMatrix = new createjs.Matrix2D(obj._transform.a, obj._transform.b, obj._transform.c, obj._transform.d, obj._transform.tx, obj._transform.ty);
}
return shape;
}
static drawBezierElement(g, currentPoint, method, args) {
switch (method) {
case 'M':
currentPoint.x = Number(args[0]);
currentPoint.y = Number(args[1]);
g.moveTo(currentPoint.x, currentPoint.y);
break;
case 'm':
currentPoint.x += Number(args[0]);
currentPoint.y += Number(args[1]);
g.moveTo(currentPoint.x, currentPoint.y);
break;
case 'L':
currentPoint.x = Number(args[0]);
currentPoint.y = Number(args[1]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'l':
currentPoint.x += Number(args[0]);
currentPoint.y += Number(args[1]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'H':
currentPoint.x = Number(args[0]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'h':
currentPoint.x += Number(args[0]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'V':
currentPoint.y = Number(args[0]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'v':
currentPoint.y += Number(args[0]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'C':
currentPoint.x1 = Number(args[0]);
currentPoint.y1 = Number(args[1]);
currentPoint.x2 = Number(args[2]);
currentPoint.y2 = Number(args[3]);
currentPoint.x = Number(args[4]);
currentPoint.y = Number(args[5]);
g.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
break;
case 'c':
currentPoint.x1 = currentPoint.x + Number(args[0]);
currentPoint.y1 = currentPoint.y + Number(args[1]);
currentPoint.x2 = currentPoint.x + Number(args[2]);
currentPoint.y2 = currentPoint.y + Number(args[3]);
currentPoint.x += Number(args[4]);
currentPoint.y += Number(args[5]);
g.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
break;
case 'S':
if (currentPoint.x1 && currentPoint.y1 && currentPoint.x2 && currentPoint.y2) {
currentPoint.x1 = currentPoint.x - currentPoint.x2 + currentPoint.x;
currentPoint.y1 = currentPoint.y - currentPoint.y2 + currentPoint.y;
currentPoint.x2 = Number(args[0]);
currentPoint.y2 = Number(args[1]);
currentPoint.x = Number(args[2]);
currentPoint.y = Number(args[3]);
g.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
} else {
currentPoint.x1 = Number(args[0]);
currentPoint.y1 = Number(args[1]);
currentPoint.x = Number(args[2]);
currentPoint.y = Number(args[3]);
g.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
}
break;
case 's':
if (currentPoint.x1 && currentPoint.y1 && currentPoint.x2 && currentPoint.y2) {
currentPoint.x1 = currentPoint.x - currentPoint.x2 + currentPoint.x;
currentPoint.y1 = currentPoint.y - currentPoint.y2 + currentPoint.y;
currentPoint.x2 = currentPoint.x + Number(args[0]);
currentPoint.y2 = currentPoint.y + Number(args[1]);
currentPoint.x += Number(args[2]);
currentPoint.y += Number(args[3]);
g.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
} else {
currentPoint.x1 = currentPoint.x + Number(args[0]);
currentPoint.y1 = currentPoint.y + Number(args[1]);
currentPoint.x += Number(args[2]);
currentPoint.y += Number(args[3]);
g.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
}
break;
case 'Q':
currentPoint.x1 = Number(args[0]);
currentPoint.y1 = Number(args[1]);
currentPoint.x = Number(args[2]);
currentPoint.y = Number(args[3]);
g.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
break;
case 'q':
currentPoint.x1 = currentPoint.x + Number(args[0]);
currentPoint.y1 = currentPoint.y + Number(args[1]);
currentPoint.x += Number(args[2]);
currentPoint.y += Number(args[3]);
g.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
break;
case 'A':
break;
case 'a':
break;
case 'Z':
case 'z':
g.closePath();
break;
default:
break;
}
}
static requestEllipseShape(obj) {
const shape = new createjs.Shape()
const g = shape.graphics;
this.resetStyle(obj, shape);
g.drawEllipse(obj._x - obj._radiusX, obj._y - obj._radiusY, obj._radiusX * 2, obj._radiusY * 2);
if (obj._transform !== undefined && obj._transform !== null) {
shape.transformMatrix = new createjs.Matrix2D(obj._transform.a, obj._transform.b, obj._transform.c, obj._transform.d, obj._transform.tx, obj._transform.ty);
}
return shape;
}
static requestRectShape(obj) {
const shape = new createjs.Shape()
const g = shape.graphics;
this.resetStyle(obj, shape);
g.drawRoundRect(obj._x, obj._y, obj._width, obj._height, obj._cornerRadius);
if (obj._transform !== undefined && obj._transform !== null) {
shape.transformMatrix = new createjs.Matrix2D(obj._transform.a, obj._transform.b, obj._transform.c, obj._transform.d, obj._transform.tx, obj._transform.ty);
}
return shape;
}
}

View File

@@ -0,0 +1,8 @@
import { Parser } from '../parser'
import { Player } from './player'
module.exports = {
Parser,
Player,
LayaboxPlayer: Player,
}

View File

@@ -0,0 +1,281 @@
import { Renderer } from './renderer'
import { Parser } from '../parser'
const ValueAnimator = require("value-animator")
export class Player extends Laya.Sprite {
loops = 0;
clearsAfterStop = true;
fillMode = "Forward";
constructor(url, autoplay) {
super();
if (url) {
(new Parser()).load(url, (videoItem) => {
this.setVideoItem(videoItem);
if (autoplay !== false) {
this.startAnimation();
}
}, (error) => {
this._onError && this._onError(error);
})
}
this._renderer = new Renderer(this);
}
setVideoUrl(url, autoplay, success, failure) {
(new Parser()).load(url, (videoItem) => {
if (success) {
success(videoItem);
}
this.setVideoItem(videoItem);
if (autoplay !== false) {
this.startAnimation();
}
}, (error) => {
if (failure) {
failure(error);
}
this._onError && this._onError(error);
})
}
setVideoItem(videoItem) {
this._currentFrame = 0;
this._videoItem = videoItem;
this.removeChildren(0, this.numChildren);
this._addLayers();
}
setContentMode(contentMode) {
this._contentMode = contentMode;
this._update();
}
setClipsToBounds(clipsToBounds) {
this._clipsToBounds = clipsToBounds;
this._update();
}
setFrame(x, y, width, height) {
this._frame = { x, y, width, height }
this._update();
}
startAnimation(reverse) {
this.visible = true;
this.stopAnimation(false);
this._doStart(undefined, reverse, undefined);
}
startAnimationWithRange(range, reverse) {
this.visible = true;
this.stopAnimation(false);
this._doStart(range, reverse, undefined)
}
pauseAnimation() {
this.stopAnimation(false);
}
stopAnimation(clear) {
if (this._animator !== undefined) {
this._animator.stop()
}
if (clear === undefined) {
clear = this.clearsAfterStop;
}
if (clear) {
this.clear();
}
}
clear() {
this.visible = false;
}
stepToFrame(frame, andPlay) {
if (frame >= this._videoItem.frames || frame < 0) {
return;
}
this.visible = true;
this.pauseAnimation();
this._currentFrame = frame;
this._update();
if (andPlay) {
this._doStart(undefined, false, this._currentFrame)
}
}
stepToPercentage(percentage, andPlay) {
let frame = parseInt(percentage * this._videoItem.frames);
if (frame >= this._videoItem.frames && frame > 0) {
frame = this._videoItem.frames - 1;
}
this.stepToFrame(frame, andPlay);
}
setImage(urlORbase64, forKey, transform) {
this._dynamicImage[forKey] = urlORbase64;
if (transform !== undefined && transform instanceof Array && transform.length == 6) {
this._dynamicImageTransform[forKey] = transform;
}
if (this._videoItem !== undefined) {
const currentFrame = this._currentFrame;
this.removeChildren(0, this.numChildren);
this._addLayers();
this._currentFrame = currentFrame;
this._update();
}
}
setText(textORMap, forKey) {
let text = typeof textORMap === "string" ? textORMap : textORMap.text;
let size = (typeof textORMap === "object" ? textORMap.size : "14px") || "14px";
let family = (typeof textORMap === "object" ? textORMap.family : "Arial") || "Arial";
let color = (typeof textORMap === "object" ? textORMap.color : "#000000") || "#000000";
let offset = (typeof textORMap === "object" ? textORMap.offset : { x: 0.0, y: 0.0 }) || { x: 0.0, y: 0.0 };
let textLayer = new Laya.Text();
textLayer.text = text;
textLayer.fontSize = isNaN(parseInt(size.split(' ')[0])) ? 14 : parseInt(size.split(' ')[0]);;
textLayer.color = color;
textLayer.align = "center";
textLayer.valign = "middle";
if (textLayer.y !== undefined) {
textLayer.y = textLayer.y - textLayer.textHeight / 2.0;
}
textLayer.offset = offset;
this._dynamicText[forKey] = textLayer;
if (this._videoItem !== undefined) {
const currentFrame = this._currentFrame;
this.removeChildren(0, this.numChildren);
this._addLayers();
this._currentFrame = currentFrame;
this._update();
}
}
clearDynamicObjects() {
this._dynamicImage = {};
this._dynamicImageTransform = {};
this._dynamicText = {};
}
onError(callback) {
this._onError = callback;
}
onFinished(callback) {
this._onFinished = callback;
}
onFrame(callback) {
this._onFrame = callback;
}
onPercentage(callback) {
this._onPercentage = callback;
}
/**
* Private methods & properties
*/
_renderer = undefined;
_animator = undefined;
_contentMode = "AspectFit"
_videoItem = undefined;
_currentFrame = 0;
_dynamicImage = {};
_dynamicImageTransform = {};
_dynamicText = {};
_onFinished = undefined;
_onFrame = undefined;
_onPercentage = undefined;
_clipsToBounds = false;
_frame = { x: 0, y: 0, width: 0, height: 0 };
_doStart(range, reverse, fromFrame) {
this._animator = new ValueAnimator()
if (range !== undefined) {
this._animator.startValue = Math.max(0, range.location)
this._animator.endValue = Math.min(this._videoItem.frames - 1, range.location + range.length)
this._animator.duration = (this._animator.endValue - this._animator.startValue + 1) * (1.0 / this._videoItem.FPS) * 1000
}
else {
this._animator.startValue = 0
this._animator.endValue = this._videoItem.frames - 1
this._animator.duration = this._videoItem.frames * (1.0 / this._videoItem.FPS) * 1000
}
this._animator.loops = this.loops <= 0 ? Infinity : this.loops
this._animator.fillRule = this.fillMode === "Backward" ? 1 : 0
this._animator.onUpdate = (value) => {
if (this._currentFrame === Math.floor(value)) {
return;
}
this._currentFrame = Math.floor(value)
this._update()
if (typeof this._onFrame === "function") {
this._onFrame(this._currentFrame);
}
if (typeof this._onPercentage === "function") {
this._onPercentage(parseFloat(this._currentFrame + 1) / parseFloat(this._videoItem.frames));
}
}
this._animator.onEnd = () => {
if (this.clearsAfterStop === true) {
this.clear()
}
if (typeof this._onFinished === "function") {
this._onFinished();
}
}
if (reverse === true) {
this._animator.reverse(fromFrame)
}
else {
this._animator.start(fromFrame)
}
}
_addLayers() {
this._videoItem.sprites.forEach((sprite) => {
this.addChild(this._renderer.requestContentLayer(sprite));
})
this._currentFrame = 0;
this._update();
}
_resize() {
let scaleX = 1.0; let scaleY = 1.0; let translateX = 0.0; let translateY = 0.0;
let targetSize = { width: this._frame.width, height: this._frame.height };
let imageSize = this._videoItem.videoSize;
if (this._contentMode === "Fill") {
scaleX = targetSize.width / imageSize.width;
scaleY = targetSize.height / imageSize.height;
}
else if (this._contentMode === "AspectFit" || this._contentMode === "AspectFill") {
const imageRatio = imageSize.width / imageSize.height;
const viewRatio = targetSize.width / targetSize.height;
if ((imageRatio >= viewRatio && this._contentMode === "AspectFit") || (imageRatio <= viewRatio && this._contentMode === "AspectFill")) {
scaleX = scaleY = targetSize.width / imageSize.width;
translateY = (targetSize.height - imageSize.height * scaleY) / 2.0
}
else if ((imageRatio < viewRatio && this._contentMode === "AspectFit") || (imageRatio > viewRatio && this._contentMode === "AspectFill")) {
scaleX = scaleY = targetSize.height / imageSize.height;
translateX = (targetSize.width - imageSize.width * scaleX) / 2.0
}
}
this.transform = new Laya.Matrix(scaleX, 0.0, 0.0, scaleY, this._frame.x + translateX, this._frame.y + translateY);
}
_updateMask() { }
_update() {
if (this._videoItem === undefined) { return; }
this._resize();
this._updateMask();
this._renderer.drawFrame(this._currentFrame);
}
}

View File

@@ -0,0 +1,519 @@
import { BezierPath } from '../bezierPath'
import { EllipsePath } from '../ellipsePath'
import { RectPath } from '../rectPath'
const validMethods = 'MLHVCSQRZmlhvcsqrz'
class ShapeSprite extends Laya.Sprite {
customGraphics = {
currentPath: [],
};
constructor() {
super();
this.customRenderEnable = true;
}
getBounds() {
return { x: 0, y: 0, width: 3000, height: 3000 }
}
beginFill(fillStyle) {
this.customGraphics.fillStyle = fillStyle;
}
beginStroke(stroke) {
this.customGraphics.strokeStyle = stroke;
}
setStrokeStyle(width, caps, joints, miterLimit) {
this.customGraphics.lineCap = caps;
this.customGraphics.lineJoin = joints;
this.customGraphics.lineWidth = width;
this.customGraphics.miterLimit = miterLimit;
}
setStrokeDash(arr, arg) {
this.customGraphics.strokeDash = { arr, arg }
}
moveTo(x, y) {
this.customGraphics.currentPath.push(["moveTo", x, y]);
}
lineTo(x, y) {
this.customGraphics.currentPath.push(["lineTo", x, y]);
}
bezierCurveTo(x1, y1, x2, y2, x, y) {
this.customGraphics.currentPath.push(["bezierCurveTo", x1, y1, x2, y2, x, y]);
}
quadraticCurveTo(x1, y1, x, y) {
this.customGraphics.currentPath.push(["quadraticCurveTo", x1, y1, x, y]);
}
closePath() {
this.customGraphics.currentPath.push(["closePath"]);
}
drawEllipse(left, top, dX, dY) {
if (this.customGraphics.currentPath === undefined) {
this.customGraphics.currentPath = [];
}
this.customGraphics.currentPath.push(["ellipse", left, top, dX, dY]);
}
drawRoundRect(x, y, width, height, cornerRadius) {
if (this.customGraphics.currentPath === undefined) {
this.customGraphics.currentPath = [];
}
this.customGraphics.currentPath.push(["rect", x, y, width, height, cornerRadius]);
}
customRender(render, x, y) {
let tx = 0.0;
let ty = 0.0;
if (render.ctx instanceof Laya.WebGLContext2D) {
const mat = render.ctx._curMat;
tx = render.ctx._curMat.tx / render.ctx._curMat.a
ty = render.ctx._curMat.ty / render.ctx._curMat.d
}
if (typeof this.customGraphics.fillStyle === 'string') {
if (render.ctx instanceof Laya.WebGLContext2D) {
if (this.customGraphics.fillStyle.startsWith('rgba')) {
const components = this.customGraphics.fillStyle.replace('rgba(', '').replace(')').split(',');
render.ctx.fillStyle = Laya.Color.create('#' + parseInt(components[0]).toString(16) + parseInt(components[1]).toString(16) + parseInt(components[2]).toString(16))
}
else {
render.ctx.fillStyle = this.customGraphics.fillStyle;
}
}
else {
render.ctx.fillStyle = this.customGraphics.fillStyle;
}
}
if (typeof this.customGraphics.strokeStyle === 'string') {
if (render.ctx instanceof Laya.WebGLContext2D) {
if (this.customGraphics.strokeStyle.startsWith('rgba')) {
const components = this.customGraphics.strokeStyle.replace('rgba(', '').replace(')').split(',');
render.ctx.strokeStyle = Laya.Color.create('#' + parseInt(components[0]).toString(16) + parseInt(components[1]).toString(16) + parseInt(components[2]).toString(16))
}
else {
render.ctx.strokeStyle = this.customGraphics.strokeStyle;
}
}
else {
render.ctx.strokeStyle = this.customGraphics.strokeStyle;
}
}
render.ctx.lineCap = this.customGraphics.lineCap;
render.ctx.lineJoin = this.customGraphics.lineJoin;
render.ctx.lineWidth = this.customGraphics.lineWidth;
render.ctx.miterLimit = this.customGraphics.miterLimit;
if (this.customGraphics.strokeDash !== undefined) {
const { arr, arg } = this.customGraphics.strokeDash;
const newArr = [];
arr.forEach(item => newArr.push(item));
newArr.push(arg);
render.ctx.setLineDash && render.ctx.setLineDash(newArr);
}
if (this.customGraphics.currentPath instanceof Array) {
render.ctx.beginPath();
this.customGraphics.currentPath.forEach((item) => {
if (item[0] === "moveTo") {
const tPoint = { x: item[1], y: item[2] };
render.ctx.moveTo(tPoint.x, tPoint.y);
}
else if (item[0] === "lineTo") {
const tPoint = { x: item[1], y: item[2] };
render.ctx.lineTo(tPoint.x, tPoint.y);
}
else if (item[0] === "bezierCurveTo") {
const tPoint1 = { x: item[1], y: item[2] };
const tPoint2 = { x: item[3], y: item[4] };
const tPoint3 = { x: item[5], y: item[6] };
render.ctx.bezierCurveTo(tPoint1.x, tPoint1.y, tPoint2.x, tPoint2.y, tPoint3.x, tPoint3.y);
}
else if (item[0] === "quadraticCurveTo") {
const tPoint1 = { x: item[1], y: item[2] };
const tPoint2 = { x: item[3], y: item[4] };
render.ctx.quadraticCurveTo(tPoint1.x, tPoint1.y, tPoint2.x, tPoint2.y);
}
else if (item[0] === "closePath") {
render.ctx.closePath();
}
else if (item[0] === "ellipse") {
let x = item[1];
let y = item[2];
let w = item[3];
let h = item[4];
var kappa = .5522848,
ox = (w / 2) * kappa,
oy = (h / 2) * kappa,
xe = x + w,
ye = y + h,
xm = x + w / 2,
ym = y + h / 2;
render.ctx.beginPath();
render.ctx.moveTo(x, ym);
render.ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
render.ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
render.ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
render.ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
}
else if (item[0] === "rect") {
const tPoint = { x: item[1], y: item[2] };
let x = tPoint.x;
let y = tPoint.y;
let width = item[3];
let height = item[4];
let radius = item[5];
render.ctx.moveTo(x + radius, y);
render.ctx.lineTo(x + width - radius, y);
render.ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
render.ctx.lineTo(x + width, y + height - radius);
render.ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
render.ctx.lineTo(x + radius, y + height);
render.ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
render.ctx.lineTo(x, y + radius);
render.ctx.quadraticCurveTo(x, y, x + radius, y);
render.ctx.lineTo(x, y);
render.ctx.closePath();
}
})
}
this.customGraphics.fillStyle && render.ctx.fill();
this.customGraphics.strokeStyle && render.ctx.stroke();
}
}
class VectorLayer extends Laya.Sprite {
_sprite;
_drawedFrame = 0;
_keepFrameCache = {};
constructor(sprite) {
super();
this._sprite = sprite;
this._resetKeepFrameCache();
}
stepToFrame(frame) {
if (frame < this._sprite.frames.length) {
this._drawFrame(frame);
}
}
_resetKeepFrameCache() {
this._keepFrameCache = {}
let lastKeep = 0;
this._sprite.frames.forEach((frameItem, idx) => {
if (!this._isKeepFrame(frameItem)) {
lastKeep = idx;
}
else {
this._keepFrameCache[idx] = lastKeep;
}
});
}
_requestKeepFrame(frame) {
return this._keepFrameCache[frame]
}
_isKeepFrame(frameItem) {
return frameItem.shapes && frameItem.shapes.length > 0 && frameItem.shapes[0].type === "keep";
}
_drawFrame(frame) {
if (frame < this._sprite.frames.length) {
let frameItem = this._sprite.frames[frame];
if (this._isKeepFrame(frameItem)) {
if (this._drawedFrame === this._requestKeepFrame(frame)) {
return;
}
}
this.removeChildren(0, this.numChildren);
frameItem.shapes.forEach((shape) => {
if (shape.type === "shape" && shape.pathArgs && shape.pathArgs.d) {
this.addChild(Renderer.requestBezierShape(new BezierPath(shape.pathArgs.d, shape.transform, shape.styles)));
}
else if (shape.type === "ellipse" && shape.pathArgs) {
this.addChild(Renderer.requestEllipseShape(new EllipsePath(parseFloat(shape.pathArgs.x) || 0.0, parseFloat(shape.pathArgs.y) || 0.0, parseFloat(shape.pathArgs.radiusX) || 0.0, parseFloat(shape.pathArgs.radiusY) || 0.0, shape.transform, shape.styles)));
}
else if (shape.type === "rect" && shape.pathArgs) {
this.addChild(Renderer.requestRectShape(new RectPath(parseFloat(shape.pathArgs.x) || 0.0, parseFloat(shape.pathArgs.y) || 0.0, parseFloat(shape.pathArgs.width) || 0.0, parseFloat(shape.pathArgs.height) || 0.0, parseFloat(shape.pathArgs.cornerRadius) || 0.0, shape.transform, shape.styles)));
}
})
this._drawedFrame = frame;
}
}
}
export class Renderer {
_owner;
constructor(owner) {
this._owner = owner;
}
requestContentLayer(sprite) {
let bitmap;
let contentLayer = new Laya.Sprite();
if (sprite.imageKey) {
bitmap = this._owner._dynamicImage[sprite.imageKey] || this._owner._videoItem.images[sprite.imageKey];
if (bitmap) {
contentLayer.addChild(this.requestBitmapLayer(bitmap, this._owner._dynamicImageTransform[sprite.imageKey], sprite.frames));
}
if (this._owner._dynamicText[sprite.imageKey]) {
contentLayer.textLayer = this._owner._dynamicText[sprite.imageKey];
contentLayer.addChild(this._owner._dynamicText[sprite.imageKey])
}
}
contentLayer.addChild(this.requestVectorLayer(sprite));
contentLayer.stepToFrame = (frame) => {
if (frame < sprite.frames.length) {
let frameItem = sprite.frames[frame];
if (frameItem.alpha > 0.0) {
contentLayer.alpha = frameItem.alpha;
contentLayer.visible = true;
contentLayer.transform = new Laya.Matrix(frameItem.transform.a, frameItem.transform.b, frameItem.transform.c, frameItem.transform.d, frameItem.transform.tx, frameItem.transform.ty);
contentLayer.setBounds(new Laya.Rectangle(frameItem.layout.x, frameItem.layout.y, frameItem.layout.width, frameItem.layout.height));
contentLayer.mask = undefined;
if (frameItem.maskPath) {
contentLayer.mask = Renderer.requestBezierShape(frameItem.maskPath);
}
if (contentLayer.textLayer) {
let offsetX = (contentLayer.textLayer.offset !== undefined && contentLayer.textLayer.offset.x !== undefined) ? contentLayer.textLayer.offset.x : 0;
let offsetY = (contentLayer.textLayer.offset !== undefined && contentLayer.textLayer.offset.y !== undefined) ? contentLayer.textLayer.offset.y : 0;
contentLayer.textLayer.x = (frameItem.layout.width - contentLayer.textLayer.getBounds().width) / 2.0 + offsetX;
contentLayer.textLayer.y = (frameItem.layout.height - contentLayer.textLayer.getBounds().height) / 2.0 + offsetY;
}
}
else {
contentLayer.visible = false;
}
}
for (let index = 0; index < contentLayer.numChildren; index++) {
const child = contentLayer.getChildAt(index);
child.stepToFrame && child.stepToFrame(frame);
}
}
return contentLayer;
}
requestBitmapLayer(bitmap, bitmapTransform, frames) {
let layer = new Laya.Sprite();
if (bitmap.indexOf("iVBO") === 0 || bitmap.indexOf("/9j/2w") === 0) {
layer.loadImage('data:image/png;base64,' + bitmap);
}
else {
layer.loadImage(bitmap);
}
if (bitmapTransform !== undefined) {
layer.transform = new Laya.Matrix(bitmapTransform[0], bitmapTransform[1], bitmapTransform[2], bitmapTransform[3], bitmapTransform[4], bitmapTransform[5]);
}
layer.frames = frames;
layer.stepToFrame = (frame) => { }
return layer;
}
requestVectorLayer(sprite) {
return new VectorLayer(sprite);
}
drawFrame(frame) {
for (let index = 0; index < this._owner.numChildren; index++) {
const child = this._owner.getChildAt(index);
child.stepToFrame && child.stepToFrame(frame);
}
}
static resetStyle(obj, shape) {
const styles = obj._styles;
if (!styles) { return; }
if (styles && styles.stroke) {
shape.beginStroke(`rgba(${parseInt(styles.stroke[0] * 255)}, ${parseInt(styles.stroke[1] * 255)}, ${parseInt(styles.stroke[2] * 255)}, ${styles.stroke[3]})`);
}
if (styles) {
const width = styles.strokeWidth || 0.0;
const caps = styles.lineCap || '';
const joints = styles.lineJoin || '';
const miterLimit = styles.miterLimit || '';
shape.setStrokeStyle(width, caps, joints, miterLimit, true);
}
if (styles && styles.fill) {
shape.beginFill(`rgba(${parseInt(styles.fill[0] * 255)}, ${parseInt(styles.fill[1] * 255)}, ${parseInt(styles.fill[2] * 255)}, ${styles.fill[3]})`);
}
if (styles && styles.lineDash) {
shape.setStrokeDash([styles.lineDash[0], styles.lineDash[1]], styles.lineDash[2]);
}
}
static requestBezierShape(obj) {
const shape = new ShapeSprite()
const g = shape;
this.resetStyle(obj, shape);
let currentPoint = { x: 0, y: 0, x1: 0, y1: 0, x2: 0, y2: 0 }
const d = obj._d.replace(/([a-zA-Z])/g, '|||$1 ').replace(/,/g, ' ');
d.split('|||').forEach(segment => {
if (segment.length == 0) { return; }
const firstLetter = segment.substr(0, 1);
if (validMethods.indexOf(firstLetter) >= 0) {
const args = segment.substr(1).trim().split(" ");
this.drawBezierElement(g, currentPoint, firstLetter, args);
}
})
if (obj._transform !== undefined && obj._transform !== null) {
shape.transform = new Laya.Matrix(obj._transform.a, obj._transform.b, obj._transform.c, obj._transform.d, obj._transform.tx, obj._transform.ty);
}
return shape;
}
static drawBezierElement(g, currentPoint, method, args) {
switch (method) {
case 'M':
currentPoint.x = Number(args[0]);
currentPoint.y = Number(args[1]);
g.moveTo(currentPoint.x, currentPoint.y);
break;
case 'm':
currentPoint.x += Number(args[0]);
currentPoint.y += Number(args[1]);
g.moveTo(currentPoint.x, currentPoint.y);
break;
case 'L':
currentPoint.x = Number(args[0]);
currentPoint.y = Number(args[1]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'l':
currentPoint.x += Number(args[0]);
currentPoint.y += Number(args[1]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'H':
currentPoint.x = Number(args[0]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'h':
currentPoint.x += Number(args[0]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'V':
currentPoint.y = Number(args[0]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'v':
currentPoint.y += Number(args[0]);
g.lineTo(currentPoint.x, currentPoint.y);
break;
case 'C':
currentPoint.x1 = Number(args[0]);
currentPoint.y1 = Number(args[1]);
currentPoint.x2 = Number(args[2]);
currentPoint.y2 = Number(args[3]);
currentPoint.x = Number(args[4]);
currentPoint.y = Number(args[5]);
g.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
break;
case 'c':
currentPoint.x1 = currentPoint.x + Number(args[0]);
currentPoint.y1 = currentPoint.y + Number(args[1]);
currentPoint.x2 = currentPoint.x + Number(args[2]);
currentPoint.y2 = currentPoint.y + Number(args[3]);
currentPoint.x += Number(args[4]);
currentPoint.y += Number(args[5]);
g.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
break;
case 'S':
if (currentPoint.x1 && currentPoint.y1 && currentPoint.x2 && currentPoint.y2) {
currentPoint.x1 = currentPoint.x - currentPoint.x2 + currentPoint.x;
currentPoint.y1 = currentPoint.y - currentPoint.y2 + currentPoint.y;
currentPoint.x2 = Number(args[0]);
currentPoint.y2 = Number(args[1]);
currentPoint.x = Number(args[2]);
currentPoint.y = Number(args[3]);
g.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
} else {
currentPoint.x1 = Number(args[0]);
currentPoint.y1 = Number(args[1]);
currentPoint.x = Number(args[2]);
currentPoint.y = Number(args[3]);
g.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
}
break;
case 's':
if (currentPoint.x1 && currentPoint.y1 && currentPoint.x2 && currentPoint.y2) {
currentPoint.x1 = currentPoint.x - currentPoint.x2 + currentPoint.x;
currentPoint.y1 = currentPoint.y - currentPoint.y2 + currentPoint.y;
currentPoint.x2 = currentPoint.x + Number(args[0]);
currentPoint.y2 = currentPoint.y + Number(args[1]);
currentPoint.x += Number(args[2]);
currentPoint.y += Number(args[3]);
g.bezierCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x2, currentPoint.y2, currentPoint.x, currentPoint.y);
} else {
currentPoint.x1 = currentPoint.x + Number(args[0]);
currentPoint.y1 = currentPoint.y + Number(args[1]);
currentPoint.x += Number(args[2]);
currentPoint.y += Number(args[3]);
g.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
}
break;
case 'Q':
currentPoint.x1 = Number(args[0]);
currentPoint.y1 = Number(args[1]);
currentPoint.x = Number(args[2]);
currentPoint.y = Number(args[3]);
g.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
break;
case 'q':
currentPoint.x1 = currentPoint.x + Number(args[0]);
currentPoint.y1 = currentPoint.y + Number(args[1]);
currentPoint.x += Number(args[2]);
currentPoint.y += Number(args[3]);
g.quadraticCurveTo(currentPoint.x1, currentPoint.y1, currentPoint.x, currentPoint.y);
break;
case 'A':
break;
case 'a':
break;
case 'Z':
case 'z':
g.closePath();
break;
default:
break;
}
}
static requestEllipseShape(obj) {
const shape = new ShapeSprite()
const g = shape;
this.resetStyle(obj, shape);
g.drawEllipse(obj._x - obj._radiusX, obj._y - obj._radiusY, obj._radiusX * 2, obj._radiusY * 2);
if (obj._transform !== undefined && obj._transform !== null) {
shape.transform = new Laya.Matrix(obj._transform.a, obj._transform.b, obj._transform.c, obj._transform.d, obj._transform.tx, obj._transform.ty);
}
return shape;
}
static requestRectShape(obj) {
const shape = new ShapeSprite()
const g = shape;
this.resetStyle(obj, shape);
g.drawRoundRect(obj._x, obj._y, obj._width, obj._height, obj._cornerRadius);
if (obj._transform !== undefined && obj._transform !== null) {
shape.transform = new Laya.Matrix(obj._transform.a, obj._transform.b, obj._transform.c, obj._transform.d, obj._transform.tx, obj._transform.ty);
}
return shape;
}
}

View File

@@ -0,0 +1,14 @@
export class BezierPath {
_d;
_transform;
_styles;
_shape;
constructor(d, transform, styles) {
this._d = d;
this._transform = transform;
this._styles = styles;
}
}

View File

@@ -0,0 +1,23 @@
import { BezierPath } from './bezierPath'
export class EllipsePath extends BezierPath {
_x;
_y;
_radiusX;
_radiusY;
_transform;
_styles;
constructor(x, y, radiusX, radiusY, transform, styles) {
super();
this._x = x;
this._y = y;
this._radiusX = radiusX;
this._radiusY = radiusY;
this._transform = transform;
this._styles = styles;
}
}

View File

@@ -0,0 +1,151 @@
import { BezierPath } from './bezierPath'
export class FrameEntity {
alpha = 0.0;
transform = {
a: 1.0,
b: 0.0,
c: 0.0,
d: 1.0,
tx: 0.0,
ty: 0.0,
};
layout = {
x: 0.0,
y: 0.0,
width: 0.0,
height: 0.0,
}
nx = 0.0;
ny = 0.0;
/**
* BezierPath
*/
maskPath = null;
/**
* Object[]
*/
shapes = [];
constructor(spec) {
this.alpha = parseFloat(spec.alpha) || 0.0;
if (spec.layout) {
this.layout.x = parseFloat(spec.layout.x) || 0.0;
this.layout.y = parseFloat(spec.layout.y) || 0.0;
this.layout.width = parseFloat(spec.layout.width) || 0.0;
this.layout.height = parseFloat(spec.layout.height) || 0.0;
}
if (spec.transform) {
this.transform.a = parseFloat(spec.transform.a) || 1.0;
this.transform.b = parseFloat(spec.transform.b) || 0.0;
this.transform.c = parseFloat(spec.transform.c) || 0.0;
this.transform.d = parseFloat(spec.transform.d) || 1.0;
this.transform.tx = parseFloat(spec.transform.tx) || 0.0;
this.transform.ty = parseFloat(spec.transform.ty) || 0.0;
}
if (spec.clipPath && spec.clipPath.length > 0) {
this.maskPath = new BezierPath(spec.clipPath, undefined, { fill: "#000000" });
}
if (spec.shapes) {
if (spec.shapes instanceof Array) {
spec.shapes.forEach(shape => {
shape.pathArgs = shape.args;
switch (shape.type) {
case 0:
shape.type = "shape";
shape.pathArgs = shape.shape;
break;
case 1:
shape.type = "rect";
shape.pathArgs = shape.rect;
break;
case 2:
shape.type = "ellipse";
shape.pathArgs = shape.ellipse;
break;
case 3:
shape.type = "keep";
break;
}
if (shape.styles) {
if (shape.styles.fill) {
if (typeof shape.styles.fill["r"] === "number") shape.styles.fill[0] = shape.styles.fill["r"];
if (typeof shape.styles.fill["g"] === "number") shape.styles.fill[1] = shape.styles.fill["g"];
if (typeof shape.styles.fill["b"] === "number") shape.styles.fill[2] = shape.styles.fill["b"];
if (typeof shape.styles.fill["a"] === "number") shape.styles.fill[3] = shape.styles.fill["a"];
}
if (shape.styles.stroke) {
if (typeof shape.styles.stroke["r"] === "number") shape.styles.stroke[0] = shape.styles.stroke["r"];
if (typeof shape.styles.stroke["g"] === "number") shape.styles.stroke[1] = shape.styles.stroke["g"];
if (typeof shape.styles.stroke["b"] === "number") shape.styles.stroke[2] = shape.styles.stroke["b"];
if (typeof shape.styles.stroke["a"] === "number") shape.styles.stroke[3] = shape.styles.stroke["a"];
}
let lineDash = shape.styles.lineDash || []
if (shape.styles.lineDashI > 0) {
lineDash.push(shape.styles.lineDashI)
}
if (shape.styles.lineDashII > 0) {
if (lineDash.length < 1) { lineDash.push(0) }
lineDash.push(shape.styles.lineDashII)
lineDash.push(0)
}
if (shape.styles.lineDashIII > 0) {
if (lineDash.length < 2) { lineDash.push(0); lineDash.push(0); }
lineDash[2] = shape.styles.lineDashIII
}
shape.styles.lineDash = lineDash
switch (shape.styles.lineJoin) {
case 0:
shape.styles.lineJoin = "miter";
break;
case 1:
shape.styles.lineJoin = "round";
break;
case 2:
shape.styles.lineJoin = "bevel";
break;
}
switch (shape.styles.lineCap) {
case 0:
shape.styles.lineCap = "butt";
break;
case 1:
shape.styles.lineCap = "round";
break;
case 2:
shape.styles.lineCap = "square";
break;
}
}
})
}
if (spec.shapes[0] && spec.shapes[0].type === "keep") {
this.shapes = FrameEntity.lastShapes;
}
else {
this.shapes = spec.shapes
FrameEntity.lastShapes = spec.shapes;
}
}
let llx = this.transform.a * this.layout.x + this.transform.c * this.layout.y + this.transform.tx;
let lrx = this.transform.a * (this.layout.x + this.layout.width) + this.transform.c * this.layout.y + this.transform.tx;
let lbx = this.transform.a * this.layout.x + this.transform.c * (this.layout.y + this.layout.height) + this.transform.tx;
let rbx = this.transform.a * (this.layout.x + this.layout.width) + this.transform.c * (this.layout.y + this.layout.height) + this.transform.tx;
let lly = this.transform.b * this.layout.x + this.transform.d * this.layout.y + this.transform.ty;
let lry = this.transform.b * (this.layout.x + this.layout.width) + this.transform.d * this.layout.y + this.transform.ty;
let lby = this.transform.b * this.layout.x + this.transform.d * (this.layout.y + this.layout.height) + this.transform.ty;
let rby = this.transform.b * (this.layout.x + this.layout.width) + this.transform.d * (this.layout.y + this.layout.height) + this.transform.ty;
this.nx = Math.min(Math.min(lbx, rbx), Math.min(llx, lrx));
this.ny = Math.min(Math.min(lby, rby), Math.min(lly, lry));
}
}

View File

@@ -0,0 +1,207 @@
const { ProtoMovieEntity } = require("./proto")
const assignUtils = require('pako/lib/utils/common').assign;
const inflate = require("pako/lib/inflate")
const pako = {}
assignUtils(pako, inflate);
const Uint8ToString = function (u8a) {
var CHUNK_SZ = 0x8000;
var c = [];
for (var i = 0; i < u8a.length; i += CHUNK_SZ) {
c.push(String.fromCharCode.apply(null, u8a.subarray(i, i + CHUNK_SZ)));
}
return c.join("");
}
const actions = {
loadAssets: (url, cb, failure) => {
if (typeof JSZipUtils === "object" && typeof JSZip === "function") {
if (url.toString() == "[object File]"){
actions._readBlobAsArrayBuffer(url, function (arrayBufferSVGA) {
const dataHeader = new Uint8Array(arrayBufferSVGA, 0, 4)
if (dataHeader[0] == 80 && dataHeader[1] == 75 && dataHeader[2] == 3 && dataHeader[3] == 4) {
JSZip.loadAsync(arrayBufferSVGA).then(function (zip) {
actions._decodeAssets(zip, cb);
});
}
else {
actions.load_viaProto(arrayBufferSVGA, cb, failure);
}
});
} else if(url.indexOf("data:svga/1.0;base64,") >= 0) {
var arrayBufferSVGA = actions._base64ToArrayBuffer(url.substring(21));
JSZip.loadAsync(arrayBufferSVGA).then(function (zip) {
actions._decodeAssets(zip, cb);
});
}else if(url.indexOf("data:svga/2.0;base64,") >= 0){
var arrayBufferSVGA = actions._base64ToArrayBuffer(url.substring(21));
actions.load_viaProto(arrayBufferSVGA, cb, failure);
}else{
JSZipUtils.getBinaryContent(url, function (err, data) {
if (err) {
failure && failure(err);
console.error(err);
throw err;
}
else {
const dataHeader = new Uint8Array(data, 0, 4)
if (dataHeader[0] == 80 && dataHeader[1] == 75 && dataHeader[2] == 3 && dataHeader[3] == 4) {
JSZip.loadAsync(data).then(function (zip) {
actions._decodeAssets(zip, cb);
});
}
else {
actions.load_viaProto(data, cb, failure);
}
}
});
}
}
else {
const req = new XMLHttpRequest()
req.open("GET", url, true);
req.responseType = "arraybuffer"
// load success
req.onload = () => {
actions.load_viaProto(req.response, cb, failure);
};
// load error
req.onerror = (err) => {
// Do not log to console or throw, if failure() exists
if (failure) {
failure(err);
return;
}
console.error(err);
throw err;
};
req.send()
}
},
load_viaProto: (arraybuffer, cb, failure) => {
try {
const inflatedData = pako.inflate(arraybuffer);
const movieData = ProtoMovieEntity.decode(inflatedData);
let images = {};
actions._loadImages(images, undefined, movieData, function () {
movieData.ver = "2.0";
cb({
movie: movieData,
images,
})
})
} catch (err) {
// Do not log to console or throw, if failure() exists
if (failure) {
failure(err);
return;
}
console.error(err);
throw err;
}
},
_decodeAssets: (zip, cb) => {
var version = "1.0";
if(zip.file("movie.binary")){
version = "1.5";
}
zip.file("movie.spec").async("string").then(function (spec) {
let movieData = JSON.parse(spec);
let images = {};
movieData.ver = version;
actions._loadImages(images, zip, movieData, function () {
cb({
movie: movieData,
images,
})
})
})
},
_loadImages: function (images, zip, movieData, imagesLoadedBlock) {
if (typeof movieData === "object" && movieData.$type == ProtoMovieEntity) {
var finished = true;
if (!zip) {
for (const key in movieData.images) {
if (movieData.images.hasOwnProperty(key)) {
const element = movieData.images[key];
let value;
try {
value = Uint8ToString(element);
} catch(e) {
// fix windows xp chrome 下首次执行 String.fromCharCode.apply报错问题
value = Uint8ToString(element);
}
images[key] = btoa(value);
}
}
}
else {
for (const key in movieData.images) {
if (movieData.images.hasOwnProperty(key)) {
const element = movieData.images[key];
const value = Uint8ToString(element);
if (images.hasOwnProperty(key)) {
continue;
}
finished = false;
zip.file(value + ".png").async("base64").then(function (data) {
images[key] = data;
actions._loadImages(images, zip, movieData, imagesLoadedBlock);
}.bind(this))
break;
}
}
}
finished && imagesLoadedBlock.call(this)
}
else {
var finished = true;
for (var key in movieData.images) {
if (movieData.images.hasOwnProperty(key)) {
var element = movieData.images[key];
if (images.hasOwnProperty(key)) {
continue;
}
finished = false;
zip.file(element + ".png").async("base64").then(function (data) {
images[key] = data;
actions._loadImages(images, zip, movieData, imagesLoadedBlock);
}.bind(this))
break;
}
}
finished && imagesLoadedBlock.call(this)
}
},
_base64ToArrayBuffer: (base64) => {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array( len );
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
},
_readBlobAsArrayBuffer: (blob, callback) => {
var reader = new FileReader();
reader.onload = function(e) {callback(e.target.result);};
reader.readAsArrayBuffer(blob);
}
}
module.exports = (data, cb, failure) => {
actions['loadAssets'](data, cb, failure);
}

View File

@@ -0,0 +1,24 @@
import { VideoEntity } from './videoEntity'
import MockWorker from './mockWorker'
export class Parser {
/**
* url: 资源路径
* success(VideoEntity videoItem)
*/
load(url, success, failure) {
this.loadViaWorker(url, success, failure);
}
loadViaWorker(url, success, failure) {
MockWorker(url, (data) => {
let movie = data.movie;
movie["version"] = data.ver;
let images = data.images;
let videoItem = new VideoEntity(movie, images);
success(videoItem);
}, failure)
}
}

View File

@@ -0,0 +1,5 @@
const protobuf = require("protobufjs/light")
const svgaDescriptor = JSON.parse(`{"nested":{"com":{"nested":{"opensource":{"nested":{"svga":{"options":{"objc_class_prefix":"SVGAProto","java_package":"com.opensource.svgaplayer.proto"},"nested":{"MovieParams":{"fields":{"viewBoxWidth":{"type":"float","id":1},"viewBoxHeight":{"type":"float","id":2},"fps":{"type":"int32","id":3},"frames":{"type":"int32","id":4}}},"SpriteEntity":{"fields":{"imageKey":{"type":"string","id":1},"frames":{"rule":"repeated","type":"FrameEntity","id":2},"matteKey":{"type":"string","id":3}}},"AudioEntity":{"fields":{"audioKey":{"type":"string","id":1},"startFrame":{"type":"int32","id":2},"endFrame":{"type":"int32","id":3},"startTime":{"type":"int32","id":4},"totalTime":{"type":"int32","id":5}}},"Layout":{"fields":{"x":{"type":"float","id":1},"y":{"type":"float","id":2},"width":{"type":"float","id":3},"height":{"type":"float","id":4}}},"Transform":{"fields":{"a":{"type":"float","id":1},"b":{"type":"float","id":2},"c":{"type":"float","id":3},"d":{"type":"float","id":4},"tx":{"type":"float","id":5},"ty":{"type":"float","id":6}}},"ShapeEntity":{"oneofs":{"args":{"oneof":["shape","rect","ellipse"]}},"fields":{"type":{"type":"ShapeType","id":1},"shape":{"type":"ShapeArgs","id":2},"rect":{"type":"RectArgs","id":3},"ellipse":{"type":"EllipseArgs","id":4},"styles":{"type":"ShapeStyle","id":10},"transform":{"type":"Transform","id":11}},"nested":{"ShapeType":{"values":{"SHAPE":0,"RECT":1,"ELLIPSE":2,"KEEP":3}},"ShapeArgs":{"fields":{"d":{"type":"string","id":1}}},"RectArgs":{"fields":{"x":{"type":"float","id":1},"y":{"type":"float","id":2},"width":{"type":"float","id":3},"height":{"type":"float","id":4},"cornerRadius":{"type":"float","id":5}}},"EllipseArgs":{"fields":{"x":{"type":"float","id":1},"y":{"type":"float","id":2},"radiusX":{"type":"float","id":3},"radiusY":{"type":"float","id":4}}},"ShapeStyle":{"fields":{"fill":{"type":"RGBAColor","id":1},"stroke":{"type":"RGBAColor","id":2},"strokeWidth":{"type":"float","id":3},"lineCap":{"type":"LineCap","id":4},"lineJoin":{"type":"LineJoin","id":5},"miterLimit":{"type":"float","id":6},"lineDashI":{"type":"float","id":7},"lineDashII":{"type":"float","id":8},"lineDashIII":{"type":"float","id":9}},"nested":{"RGBAColor":{"fields":{"r":{"type":"float","id":1},"g":{"type":"float","id":2},"b":{"type":"float","id":3},"a":{"type":"float","id":4}}},"LineCap":{"values":{"LineCap_BUTT":0,"LineCap_ROUND":1,"LineCap_SQUARE":2}},"LineJoin":{"values":{"LineJoin_MITER":0,"LineJoin_ROUND":1,"LineJoin_BEVEL":2}}}}}},"FrameEntity":{"fields":{"alpha":{"type":"float","id":1},"layout":{"type":"Layout","id":2},"transform":{"type":"Transform","id":3},"clipPath":{"type":"string","id":4},"shapes":{"rule":"repeated","type":"ShapeEntity","id":5}}},"MovieEntity":{"fields":{"version":{"type":"string","id":1},"params":{"type":"MovieParams","id":2},"images":{"keyType":"string","type":"bytes","id":3},"sprites":{"rule":"repeated","type":"SpriteEntity","id":4},"audios":{"rule":"repeated","type":"AudioEntity","id":5}}}}}}}}}}}`)
export const proto = protobuf.Root.fromJSON(svgaDescriptor);
export const ProtoMovieEntity = proto.lookupType("com.opensource.svga.MovieEntity");

View File

@@ -0,0 +1,24 @@
import { BezierPath } from './bezierPath'
export class RectPath extends BezierPath {
_x;
_y;
_width;
_height;
_cornerRadius;
_transform;
_styles;
constructor(x, y, width, height, cornerRadius, transform, styles) {
super();
this._x = x
this._y = y
this._width = width
this._height = height
this._cornerRadius = cornerRadius
this._transform = transform
this._styles = styles
}
}

View File

@@ -0,0 +1,33 @@
import { FrameEntity } from './frameEntity'
import { BezierPath } from './bezierPath'
import { RectPath } from './rectPath'
import { EllipsePath } from './ellipsePath'
export class SpriteEntity {
/**
* string
*/
matteKey = null
/**
* string
*/
imageKey = null
/**
* FrameEntity[]
*/
frames = []
constructor(spec) {
this.matteKey = spec.matteKey;
this.imageKey = spec.imageKey;
if (spec.frames) {
this.frames = spec.frames.map((obj) => {
return new FrameEntity(obj)
})
}
}
}

View File

@@ -0,0 +1,82 @@
import { SpriteEntity } from './spriteEntity'
const { ProtoMovieEntity } = require("./proto")
export class VideoEntity {
/**
* SVGA 文件版本
*/
version = "";
/**
* 影片尺寸
*/
videoSize = {
width: 0.0,
height: 0.0,
};
/**
* 帧率
*/
FPS = 20;
/**
* 帧数
*/
frames = 0;
/**
* Bitmaps
*/
images = {};
/**
* SpriteEntity[]
*/
sprites = []
/**
* AudioEntity[]
*/
audios = []
constructor(spec, images) {
if (typeof spec === "object" && spec.$type == ProtoMovieEntity) {
if (typeof spec.params === "object") {
this.version = spec.ver;
this.videoSize.width = spec.params.viewBoxWidth || 0.0;
this.videoSize.height = spec.params.viewBoxHeight || 0.0;
this.FPS = spec.params.fps || 20;
this.frames = spec.params.frames || 0;
}
this.resetSprites(spec)
this.audios = spec.audios
}
else if (spec) {
if (spec.movie) {
if (spec.movie.viewBox) {
this.videoSize.width = parseFloat(spec.movie.viewBox.width) || 0.0;
this.videoSize.height = parseFloat(spec.movie.viewBox.height) || 0.0;
}
this.version = spec.ver;
this.FPS = parseInt(spec.movie.fps) || 20;
this.frames = parseInt(spec.movie.frames) || 0;
}
this.resetSprites(spec)
}
if (images) {
this.images = images
}
}
resetSprites(spec) {
if (spec.sprites instanceof Array) {
this.sprites = spec.sprites.map((obj) => {
return new SpriteEntity(obj)
})
}
}
}

View File

@@ -0,0 +1,34 @@
var path = require('path');
var webpack = require('webpack')
module.exports = {
entry: {
"svga.min": "./src/Canvas/index.js",
"svga.createjs.min": "./src/CreateJS/index.js",
"svga.layabox.min": "./src/LayaBox/index.js",
},
output: {
path: __dirname,
filename: "build/[name].js",
libraryTarget: 'umd',
library: 'SVGA',
},
module: {
rules: [
{
test: path.join(__dirname, 'src'),
loader: 'babel-loader',
query: {
presets: ['es2015', "stage-0"]
}
}
],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
minimize: true,
output: { comments: false },
})
],
}