Commit 91796154 authored by wjf's avatar wjf

l

parents
Pipeline #160912 failed with stages
in 0 seconds
# 所有空行或者以注释符号 # 开头的行都会被 Git 忽略。
# 可以使用标准的 glob 模式匹配。
# 匹配模式最后跟反斜杠(/)说明要忽略的是目录。
# 要忽略指定模式以外的文件或目录,可以在模式前加上惊叹号(! )取反。
# 所谓的 glob 模式是指 shell 所使用的简化了的正则表达式。星号(*)匹配零个或多个任
# 意字符; [abc] 匹配任何一个列在方括号中的字符(这个例子要么匹配一个 a,要么匹配一
# 个 b,要么匹配一个 c);问号(?)只匹配一个任意字符;如果在方括号中使用短划线分
# 隔两个字符,表示所有在这两个字符范围内的都可以匹配(比如 [0-9] 表示匹配所有 0 到
# 9 的数字)。
# 书上的一个例子
# #此为注释 – 将被 Git 忽略
# *.a
# 忽略所有 .a 结尾的文件
# !lib.a
# 但 lib.a 除外
# /TODO
# 仅仅忽略项目根目录下的 TODO 文件,不包括 subdir/TODO
# build/
# 忽略 build/ 目录下的所有文件
# doc/*.txt
# 会忽略 doc/notes.txt 但不包括 doc/server/arch.txt
node_modules
node_modules/*
tests/*
{
"liveServer.settings.port": 5502
}
\ No newline at end of file
# 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 Forward,optional Forward / Backward,fillMode = Forward,Animation will pause on last frame while finished,fillMode = 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>
```
## 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 以重现问题)
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.
\ No newline at end of file
# 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 Forward,optional Forward / Backward,fillMode = Forward,Animation will pause on last frame while finished,fillMode = 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.
# SVGAPlayer-Web
预览svga动画网址 http://svga.io/svga-preview.html
### 支持 SVGA-Format 1.x 格式
如果你需要播放 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>
```
#白鹭引擎使用 在白鹭的js后加下面脚本
<script src="libs/svga.egret.min.js"></script>
```js
var parser = new SVGA.Parser();
parser.load("../egret/loading五神兽最终版.svga", (videoItem) => {
//具体用法SVGA.d.ts文件有
var mv = new SVGA.EgretMovieClip(videoItem)
// mv.lockStep=true;
// mv.play()
// mv.gotoAndPlay(30, true)
// mv.gotoAndStop(10)
// mv.startAniRange
mv.gotoAndPlay(1, true)
this.addChild(mv);
let fun
mv.addEventListener(egret.Event.COMPLETE, fun = function () {
console.log("播放完成")
// mv.removeEventListener(egret.Event.COMPLETE,fun,this)
// mv.stop()
// mv.startAniRange(30,60);
}, this)
}, function (error) {
alert(error.message);
})
## 使用指南
canvas形式使用
### 手动加载
添加 ```<script src="https://cdn.jsdelivr.net/npm/svgaplayerweb@2.3.0/build/svga.min.js"></script>``` your.html 页面
你可以自行创建 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 元素添加以下属性
```html
<div src="rose_2.0.0.svga" loops="0" clearsAfterStop="true" style="styles..."></div>
```
动画会在页面加载完成后播放
### 动态图像
你可以动态替换动画中的指定元素,询问你的动画设计师以获取 ImageKey。
* 用于替换的图片,宽、高必须与原图一致。
* setImage 操作必须在 startAnimation 之前执行。
```
player.setImage('http://yourserver.com/xxx.png', 'ImageKey');
```
### 动态文本
你可以在指定元素上添加文本,询问你的动画设计师以获取 ImageKey。
* setText 操作必须在 startAnimation 之前执行。
```
player.setText('Hello, World!', 'ImageKey');
```
```
player.setText({
text: 'Hello, World!,
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: "ScaleToFill" | "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, font: 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>
```
export as namespace SVGA;
declare global {
const SVGA: {
Parser: typeof Parser,
EgretMovieClip: typeof EgretMovieClip,
}
}
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 EgretMovieClip {
lockStep: boolean;
readonly currentFrame: number;
readonly isPlaying: boolean;
readonly isFront: boolean;
totalFrames: number;
/**
* 停止
*/
stop(): void;
/**
* 播放
*/
play(): void;
nextFrame(): void;
prevFrame(): void;
/**
* 停在指定帧
* @param frameIndex
*/
gotoAndStop(frameIndex: number): void;
/**
*
* @param frameIndex 1开始
* @param isFront 默认true正向播放
*/
gotoAndPlay(frameIndex: number, isFront: boolean): void;
readonly isInTimeFrame: boolean;
/**
* 帧数范围播放
* @param beginFrame 默认第一帧
* @param endFrame 默认最后一帧
* @param loops 默认0,表示无限循环
* @param callback 所有播放完的回调
*/
startAniRange(beginFrame: number, endFrame: number, loops: number, callback?: Function): void
constructor(mv: VideoEntity)
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
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
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "svgaplayerweb",
"version": "2.3.0",
"repository": {
"type": "git",
"url": "https://github.com/yyued/SVGAPlayer-Web.git"
},
"main": "./build/svga.min.js",
"types": "index.d.ts",
"scripts": {
"start": "http-server ./ & webpack -w & open http://127.0.0.1:8080/tests/",
"build": "webpack"
},
"author": "YYUED",
"license": "Apache License 2.0",
"dependencies": {},
"devDependencies": {
"pako": "^1.0.6",
"protobufjs": "^6.8.0",
"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",
"uglify-js": "^3.1.2",
"value-animator": "git+https://github.com/yyued/value-animator.git",
"webpack": "^3.6.0"
}
}
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);
}
}
}
}
\ No newline at end of file
import { Parser } from '../parser'
import { Player } from './player'
import { AutoLoader } from './autoLoader'
module.exports = {
Parser,
Player,
autoload: AutoLoader.autoload,
}
AutoLoader.autoload();
\ No newline at end of file
'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 : "") || "";
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);
}
}
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();
}
}
/**
* @class MovieClip
* @since 1.0.0
* @public
* @extends Container
*/
export class MovieClip extends egret.DisplayObjectContainer {
/**
* 锁步将按时间间隔来执行动画
* 有可能捕捉不到完成事件
*/
lockStep = false;
/**
* mc的当前帧,从1开始
* @property currentFrame
* @public
* @since 1.0.0
* @type {number}
* @default 1
* @readonly
*/
get currentFrame() {
return this._curFrame;
}
/**
* @property _curFrame
* @type {number}
* @private
* @since 2.0.0
* @default 1
*/
_curFrame = 1;
/**
* 当前动画是否处于播放状态
* @property isPlaying
* @readOnly
* @public
* @since 1.0.0
* @type {boolean}
* @default true
* @readonly
*/
get isPlaying() {
return this._isPlaying;
}
/**
* @property _isPlaying
* @type {boolean}
* @private
* @since 2.0.0
* @default true
*/
_isPlaying = true;
/**
* 动画的播放方向,是顺着播还是在倒着播
* @property isFront
* @public
* @since 1.0.0
* @type {boolean}
* @default true
* @readonly
*/
get isFront() {
return this._isFront;
}
/**
* @property _isFront
* @type {boolean}
* @private
* @default true
*/
_isFront = true;
/**
* 当前动画的总帧数
* @property totalFrames
* @public
* @since 1.0.0
* @type {number}
* @default 1
* @readonly
*/
totalFrames;
loops = 0;
/**
* 所有textures缓存
*/
textures = {};
/**
* 锁步的时间间隔,按fps定,毫秒
*/
timeInterval;
/**
* 前提引擎按60设置
*/
deltaFrame;
/**
* 中间帧计时
*/
frameCount = 0;
/**
* 构造函数
* @method MovieClip
* @public
* @since 1.0.0
*/
constructor(mv) {
super();
let s = this;
//初始化
if (mv) {
s.init(mv);
} else {
s.totalFrames = 0;
}
}
/**
* 可以手动用init,
* @param mv
*/
init(mv) {
//记录基本信息,fps,每秒输出帧数,frames,总帧数,videoSize暂时不管
//如果fps小于60怎么处理。update时怎么处理
this.timeInterval = 1000 / mv.FPS;
this.startTime = Date.now();
this.startFrame = 1;
this.totalFrames = mv.frames
//间隔帧数,
this.deltaFrame = 60 / mv.FPS;
this.frameCount = this.deltaFrame;
this._curFrame = 1;
//缓存所有图片
var self = this;
const images = mv.images;
let countAll = Object.getOwnPropertyNames(images).length;
let count = 0;
for (let key in images) {
var bitmap = images[key];
// let imgTag = document.createElement('img');
let imgTag = new Image();
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)
// }
// }
}
//必须加载完成才行
imgTag.onload = function () {
count++;
var bitmapData = new egret.BitmapData(backCanvas || imgTag);
var texture = new egret.Texture();
texture.bitmapData = bitmapData;
self.textures[key] = texture;
if (count == countAll) {
self.initChildren(mv.sprites);
//到时找替代的方法,用这个去循环好像,移除了还在执行
self.addEventListener(egret.Event.ENTER_FRAME, function () {
self.updateFrame()
}, self)
}
}
// Texture.addToCache(this.textures[key], key)
}
}
initChildren(sprites) {
for (var i = 0, len = sprites.length; i < len; i++) {
var ele = sprites[i];
if (ele.imageKey) {
var child
var splitArr = ele.imageKey.split("_");
//需要标记的,预留其他类型
if (splitArr[1] && splitArr[1] == "spr") {
child = new egret.Bitmap(this.textures[ele.imageKey]);
this[splitArr[0]] = child;
}
//一般不需要标记的
else {
child = new egret.Bitmap(this.textures[ele.imageKey]);
}
//透明度处理
if (ele.frames[0].alpha < 0.05) {
child.visible = false;
} else {
child.alpha = ele.frames[0].alpha;
}
child["frames"] = ele.frames;
var transform = ele.frames[0].transform
child.matrix = new egret.Matrix().copyFrom(transform);
// child.x = 0;
// child.y = 0;
this.addChild(child)
}
}
// console.log(this)
}
/**
* 调用止方法将停止当前帧
* @method stop
* @public
* @since 1.0.0
*/
stop() {
let s = this;
s._isPlaying = false;
}
/**
* 将播放头向后移一帧并停在下一帧,如果本身在最后一帧则不做任何反应
* @method nextFrame
* @since 1.0.0
* @public
*/
nextFrame() {
let s = this;
if (s._curFrame < s.totalFrames) {
s._curFrame++;
}
s._isPlaying = false;
}
/**
* 将播放头向前移一帧并停在下一帧,如果本身在第一帧则不做任何反应
* @method prevFrame
* @since 1.0.0
* @public
*/
prevFrame() {
let s = this;
if (s._curFrame > 1) {
s._curFrame--;
}
s._isPlaying = false;
}
/**
* 将播放头跳转到指定帧并停在那一帧,如果本身在第一帧则不做任何反应
* @method gotoAndStop
* @public
* @since 1.0.0
* @param {number} frameIndex 批定帧的帧数或指定帧的标签名
*/
gotoAndStop(frameIndex) {
let s = this;
s._isPlaying = false;
if (frameIndex > s.totalFrames) {
frameIndex = s.totalFrames;
}
if (frameIndex < 1) {
frameIndex = 1;
}
s._curFrame = Math.round(frameIndex);
}
/**
* 如果当前时间轴停在某一帧,调用此方法将继续播放.
* @method play
* @public
* @since 1.0.0
*/
play(isFront) {
let s = this;
s.frameCount = s.deltaFrame;
s.startTime = Date.now();
s.startFrame = s._curFrame;
s._isPlaying = true;
s._isFront = isFront === undefined ? true : isFront;
}
/**
* @property _lastFrame
* @type {number}
* @private
* @default 0
*/
_lastFrame = 0;
/**
* 刚执行到的帧数,用于帧监听时判断用
* 不是60fps的videoItem的中间有几帧curFrame会不变,判断只执行一次监听时会出错,刚好动画满帧60fps时就无所谓
*/
get isInTimeFrame() {
//相等时就是刚开始的curFrame
return this.frameCount == this.deltaFrame;
}
/**
* 将播放头跳转到指定帧并从那一帧开始继续播放
* @method gotoAndPlay
* @public
* @since 1.0.0
* @param {number} frameIndex 批定帧的帧数或指定帧的标签名
* @param {boolean} isFront 跳到指定帧后是向前播放, 还是向后播放.不设置些参数将默认向前播放
*/
gotoAndPlay(frameIndex, isFront = true) {
let s = this;
s._isFront = isFront === undefined ? true : isFront;
s._isPlaying = true;
if (frameIndex > s.totalFrames) {
frameIndex = s.totalFrames;
}
if (frameIndex < 1) {
frameIndex = 1;
}
s.frameCount = s.deltaFrame;
s.startTime = Date.now();
s._curFrame = frameIndex;
s.startFrame = s._curFrame;
}
/**
* 播放范围动画,
* @param beginFrame 开始帧
* @param endFrame 结束帧
* @param loops 0一直循环
*/
startAniRange(
beginFrame,
endFrame,
loops,
callback
) {
beginFrame = beginFrame || 1;
endFrame = endFrame || this.totalFrames;
loops = loops || 0;
if (beginFrame < 1) {
beginFrame = 1;
}
if (beginFrame > this.totalFrames) {
beginFrame = this.totalFrames;
}
if (endFrame < 1) {
endFrame = 1;
}
if (endFrame > this.totalFrames) {
endFrame = this.totalFrames;
}
if (beginFrame === endFrame) {
this.gotoAndStop(beginFrame)
//如果相等
return
} else if (beginFrame < endFrame) {
this._isFront = true;
} else {
this._isFront = false;
var temp = beginFrame;
beginFrame = endFrame;
endFrame = temp;
}
this._curFrame = beginFrame;
//赋值count最大
this.frameCount = this.deltaFrame;
this.startTime = Date.now();
this.startFrame = this._curFrame;
this._isPlaying = true;
let func;
let loopCount = loops ? (loops + 0.5 >> 0) : Infinity;
this.addEventListener(egret.Event.ENTER_FRAME, func = function (e) {
if (e.target._isFront) {
if (e.target.currentFrame >= endFrame /*&& e.target.isInTimeFrame*/) {
e.target.gotoAndPlay(beginFrame)
loopCount--
if (loopCount == 0) {
e.target.gotoAndStop(endFrame);
e.target.removeEventListener(egret.Event.ENTER_FRAME, func, this);
callback && callback();
}
}
} else {
if (e.target.currentFrame <= beginFrame /*&& e.target.isInTimeFrame*/) {
e.target.gotoAndPlay(endFrame, false);
loopCount--
if (loopCount == 0) {
e.target.gotoAndStop(beginFrame);
e.target.removeEventListener(egret.Event.ENTER_FRAME, func, this);
callback && callback();
}
}
}
}, this)
}
/**
* 开始时间,每次有play的时候就需要
* 锁步思想,设置开始时间,后面每帧实际时间与开始时间相减,加上开始帧数,得到当前帧数
*
*/
startTime;
/**
* 开始时的frame(锁步时用)
*/
startFrame;
/**
* 上一次的DeltaFrame(锁步时用)
*/
lastDeltaFrame
commonDeltaTime = 1000 / 60;
updateFrame() {
var s = this;
//1帧的时候也有相应的frameCount,无用,return
if (s.totalFrames == 0 || s.totalFrames == 1) return;
let isNeedUpdate = false;
if (s._lastFrame != s._curFrame) {
//帧不相等
isNeedUpdate = true;
s._lastFrame = s._curFrame;
} else {
if (s._isPlaying) {
if (s.lockStep) {
isNeedUpdate = s.getCurFrameWhenLockStep();
} else {
if (--s.frameCount == 0) {
s.frameCount = s.deltaFrame;
isNeedUpdate = true;
if (s._isFront) {
s._curFrame++;
if (s._curFrame > s.totalFrames) {
s._curFrame = 1;
}
} else {
s._curFrame--;
if (s._curFrame < 1) {
s._curFrame = s.totalFrames;
}
}
s._lastFrame = s._curFrame;
}
}
}
}
//如果需要更新
if (isNeedUpdate) {
//对每个child还原对应的transform,alpha为0的默认visible设为false,避免计算
for (var i = 0, len = s.$children.length; i < len; i++) {
var child = s.$children[i]
//只修改动画加入的child,不修改手动加入的,,所以想要修改动画中的元素属性,直接去掉frames属性,将不会执行动画
if (child["frames"] && child["frames"][s._curFrame - 1]) {
var frame = child["frames"][s._curFrame - 1];
//layout不晓得干嘛用,暂不管
if (frame.alpha < 0.05) {
child.visible = false;
} else {
child.visible = true;
child.alpha = frame.alpha;
//先判断transform是否相等
if (!child.matrix.equals(frame.transform)) {
child.matrix = new egret.Matrix().copyFrom(frame.transform);
}
}
}
}
//事件播放结束监听,不确定白鹭是否是COMPLETE,待试验
if (!s.lockStep) {
if (((s._curFrame == 1 && !s._isFront) || (s._curFrame == s.totalFrames && s._isFront)) && s.hasEventListener(egret.Event.COMPLETE)) {
s.dispatchEvent(new egret.Event(egret.Event.COMPLETE));
}
} else {
//锁步的时候另外判断
if (s._endMark && s.hasEventListener(egret.Event.COMPLETE)) {
s.dispatchEvent(new egret.Event(egret.Event.COMPLETE));
}
}
}
}
getCurFrameWhenLockStep() {
var dateNow = Date.now()
//相差
var deltaFrame = ((dateNow - this.startTime) / this.timeInterval) >> 0;
//间隔帧数与上一帧一致
if (deltaFrame == this.lastDeltaFrame) {
//设置不等
this.frameCount = 0;
return false
}
this._endMark = false;
//相等,刚好执行切换
this.frameCount = this.deltaFrame;
this.lastDeltaFrame = deltaFrame
if (this._isFront) {
//取余数
this._curFrame = (this.startFrame + deltaFrame) % this.totalFrames;
if (this._curFrame == 0) {
this._curFrame = this.totalFrames;
this._endMark = true;
}
//当上一帧大于_curFrame,并且上一帧不是totalFrames时,说明跳过了最后一帧
else if (this._lastFrame > this._curFrame &&
this._lastFrame != this.totalFrames) {
this._endMark = true;
}
} else {
this._curFrame = (this.startFrame - deltaFrame) % this.totalFrames;
if (this._curFrame == 0) {
this._curFrame = this.totalFrames;
} else if (this._curFrame < 0) {
this._curFrame += this.totalFrames;
}
if (this._curFrame == 1) {
this._endMark = true;
}
//当上一帧小于_curFrame,并且上一帧不是1时,说明跳过了第一帧
else if (this._lastFrame < this._curFrame &&
this._lastFrame != 1) {
this._endMark = true;
}
}
this._lastFrame = this._curFrame;
return true
}
}
import { Parser } from '../parser'
import { MovieClip } from './MovieClip'
module.exports = {
Parser,
// Player,
EgretMovieClip: MovieClip,
}
\ No newline at end of file
export class BezierPath {
_d;
_transform;
_styles;
_shape;
constructor(d, transform, styles) {
this._d = d;
this._transform = transform;
this._styles = styles;
}
}
\ No newline at end of file
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;
}
}
\ No newline at end of file
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));
}
}
\ No newline at end of file
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"
req.onloadend = () => {
actions.load_viaProto(req.response, cb, failure);
}
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) {
failure && failure(err);
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];
const 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);
}
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)
}
}
\ No newline at end of file
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");
\ No newline at end of file
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
}
}
\ No newline at end of file
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)
})
}
}
}
\ No newline at end of file
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)
})
}
}
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
<html>
<body style="text-align: center">
<div>
<div id="testCanvas" style="background-color: #000000; width: 500px; height: 500px; margin: auto"></div>
<!-- <canvas id="testCanvas" width="500" height="500" style="background-color: #000000; "></canvas> -->
</div>
<script src="https://cdn.jsdelivr.net/npm/howler@2.0.15/dist/howler.core.min.js"></script>
<!--[if lt IE 10]>
<script src="../build/svga.ie.min.js"></script>
<![endif]-->
<!--[if gte IE 10]><!-->
<!-- <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> -->
<script src="../build/svga.min.js"></script>
<!--<![endif]-->
<script>
var parser = new SVGA.Parser('#testCanvas')
var player = new SVGA.Player('#testCanvas')
parser.load("./samples/angel.svga", function (videoItem) {
// player.setImage('./samples/avatar.png', '99')
player.setVideoItem(videoItem);
player.startAnimation();
// player.startAnimationWithRange({location: 20, length: 1}, false);
}, function (error) {
alert(error.message);
})
</script>
</body>
</html>
\ No newline at end of file
<html>
<body style="text-align: center">
<div id="test">
<canvas id="demoCanvas" width="750" height="750" style="background-color: #000000"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/createjs@1.0.1/builds/1.0.0/createjs.min.js"></script>
<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>
<script src="../build/svga.createjs.min.js"></script>
<script>
var sprite = new SVGA.Player('./samples/angel.svga');
sprite.onError((err) => {
console.error(err)
})
var stage = new createjs.Stage('demoCanvas');
sprite.setFrame(0, 0, 750, 750);
// sprite.setContentMode("AspectFill")
stage.addChild(sprite);
stage.update();
</script>
</body>
</html>
\ No newline at end of file
/*!
* svga.lite.min.js
*
* Version: 1.1.1
* Time: 2019-04-10 10:14
* Document: https://github.com/yyued/SVGAPlayer-Web/tree/lite
* (c) 2019 YY.UEDC
* Released under the MIT License.
*/
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.SVGA=e():t.SVGA=e()}(window,function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=49)}([function(t,e){var r=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=r)},function(t,e){var r=t.exports={version:"2.6.5"};"number"==typeof __e&&(__e=r)},function(t,e,r){var n=r(0),o=r(1),i=r(10),a=r(8),s=r(12),u=function(t,e,r){var c,f,l,p=t&u.F,h=t&u.G,d=t&u.S,v=t&u.P,y=t&u.B,m=t&u.W,_=h?o:o[e]||(o[e]={}),x=_.prototype,b=h?n:d?n[e]:(n[e]||{}).prototype;for(c in h&&(r=e),r)(f=!p&&b&&void 0!==b[c])&&s(_,c)||(l=f?b[c]:r[c],_[c]=h&&"function"!=typeof b[c]?r[c]:y&&f?i(l,n):m&&b[c]==l?function(t){var e=function(e,r,n){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,r)}return new t(e,r,n)}return t.apply(this,arguments)};return e.prototype=t.prototype,e}(l):v&&"function"==typeof l?i(Function.call,l):l,v&&((_.virtual||(_.virtual={}))[c]=l,t&u.R&&x&&!x[c]&&a(x,c,l)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,t.exports=u},function(t,e,r){var n=r(35)("wks"),o=r(36),i=r(0).Symbol,a="function"==typeof i;(t.exports=function(t){return n[t]||(n[t]=a&&i[t]||(a?i:o)("Symbol."+t))}).store=n},function(t,e){t.exports=function(t){return t&&t.__esModule?t:{default:t}}},function(t,e,r){t.exports=r(50)},function(t,e,r){var n=r(9);t.exports=function(t){if(!n(t))throw TypeError(t+" is not an object!");return t}},function(t,e,r){t.exports=!r(15)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,r){var n=r(11),o=r(21);t.exports=r(7)?function(t,e,r){return n.f(t,e,o(1,r))}:function(t,e,r){return t[e]=r,t}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,r){var n=r(14);t.exports=function(t,e,r){if(n(t),void 0===e)return t;switch(r){case 1:return function(r){return t.call(e,r)};case 2:return function(r,n){return t.call(e,r,n)};case 3:return function(r,n,o){return t.call(e,r,n,o)}}return function(){return t.apply(e,arguments)}}},function(t,e,r){var n=r(6),o=r(29),i=r(30),a=Object.defineProperty;e.f=r(7)?Object.defineProperty:function(t,e,r){if(n(t),e=i(e,!0),n(r),o)try{return a(t,e,r)}catch(t){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(t[e]=r.value),t}},function(t,e){var r={}.hasOwnProperty;t.exports=function(t,e){return r.call(t,e)}},function(t,e){t.exports={}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e,r){t.exports=r(53)},function(t,e){t.exports=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,r){var n=r(61),o=r(17);t.exports=function(t){return n(o(t))}},function(t,e){var r={}.toString;t.exports=function(t){return r.call(t).slice(8,-1)}},function(t,e,r){var n=r(9),o=r(0).document,i=n(o)&&n(o.createElement);t.exports=function(t){return i?o.createElement(t):{}}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e){var r=Math.ceil,n=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?n:r)(t)}},function(t,e){t.exports=!0},function(t,e,r){var n=r(35)("keys"),o=r(36);t.exports=function(t){return n[t]||(n[t]=o(t))}},function(t,e,r){var n=r(11).f,o=r(12),i=r(3)("toStringTag");t.exports=function(t,e,r){t&&!o(t=r?t:t.prototype,i)&&n(t,i,{configurable:!0,value:e})}},function(t,e,r){"use strict";var n=r(14);function o(t){var e,r;this.promise=new t(function(t,n){if(void 0!==e||void 0!==r)throw TypeError("Bad Promise constructor");e=t,r=n}),this.resolve=n(e),this.reject=n(r)}t.exports.f=function(t){return new o(t)}},function(t,e){t.exports="\t\n\v\f\r   ᠎              \u2028\u2029\ufeff"},function(t,e,r){"use strict";(0,r(4)(r(5)).default)(e,"__esModule",{value:!0});var n=function(){return function(t,e,r){this._d=t,this._transform=e,this._styles=r}}();e.default=n},function(t,e,r){t.exports=!r(7)&&!r(15)(function(){return 7!=Object.defineProperty(r(20)("div"),"a",{get:function(){return 7}}).a})},function(t,e,r){var n=r(9);t.exports=function(t,e){if(!n(t))return t;var r,o;if(e&&"function"==typeof(r=t.toString)&&!n(o=r.call(t)))return o;if("function"==typeof(r=t.valueOf)&&!n(o=r.call(t)))return o;if(!e&&"function"==typeof(r=t.toString)&&!n(o=r.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},function(t,e,r){"use strict";var n=r(23),o=r(2),i=r(57),a=r(8),s=r(13),u=r(58),c=r(25),f=r(64),l=r(3)("iterator"),p=!([].keys&&"next"in[].keys()),h=function(){return this};t.exports=function(t,e,r,d,v,y,m){u(r,e,d);var _,x,b,g=function(t){if(!p&&t in O)return O[t];switch(t){case"keys":case"values":return function(){return new r(this,t)}}return function(){return new r(this,t)}},w=e+" Iterator",S="values"==v,k=!1,O=t.prototype,P=O[l]||O["@@iterator"]||v&&O[v],T=P||g(v),F=v?S?g("entries"):T:void 0,E="Array"==e&&O.entries||P;if(E&&(b=f(E.call(new t)))!==Object.prototype&&b.next&&(c(b,w,!0),n||"function"==typeof b[l]||a(b,l,h)),S&&P&&"values"!==P.name&&(k=!0,T=function(){return P.call(this)}),n&&!m||!p&&!k&&O[l]||a(O,l,T),s[e]=T,s[w]=h,v)if(_={values:S?T:g("values"),keys:y?T:g("keys"),entries:F},m)for(x in _)x in O||i(O,x,_[x]);else o(o.P+o.F*(p||k),e,_);return _}},function(t,e,r){var n=r(6),o=r(59),i=r(37),a=r(24)("IE_PROTO"),s=function(){},u=function(){var t,e=r(20)("iframe"),n=i.length;for(e.style.display="none",r(38).appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),u=t.F;n--;)delete u.prototype[i[n]];return u()};t.exports=Object.create||function(t,e){var r;return null!==t?(s.prototype=n(t),r=new s,s.prototype=null,r[a]=t):r=u(),void 0===e?r:o(r,e)}},function(t,e,r){var n=r(60),o=r(37);t.exports=Object.keys||function(t){return n(t,o)}},function(t,e,r){var n=r(22),o=Math.min;t.exports=function(t){return t>0?o(n(t),9007199254740991):0}},function(t,e,r){var n=r(1),o=r(0),i=o["__core-js_shared__"]||(o["__core-js_shared__"]={});(t.exports=function(t,e){return i[t]||(i[t]=void 0!==e?e:{})})("versions",[]).push({version:n.version,mode:r(23)?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(t,e){var r=0,n=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++r+n).toString(36))}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,r){var n=r(0).document;t.exports=n&&n.documentElement},function(t,e,r){var n=r(17);t.exports=function(t){return Object(n(t))}},function(t,e,r){var n=r(19),o=r(3)("toStringTag"),i="Arguments"==n(function(){return arguments}());t.exports=function(t){var e,r,a;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(r=function(t,e){try{return t[e]}catch(t){}}(e=Object(t),o))?r:i?n(e):"Object"==(a=n(e))&&"function"==typeof e.callee?"Arguments":a}},function(t,e,r){var n=r(6),o=r(14),i=r(3)("species");t.exports=function(t,e){var r,a=n(t).constructor;return void 0===a||null==(r=n(a)[i])?e:o(r)}},function(t,e,r){var n,o,i,a=r(10),s=r(75),u=r(38),c=r(20),f=r(0),l=f.process,p=f.setImmediate,h=f.clearImmediate,d=f.MessageChannel,v=f.Dispatch,y=0,m={},_=function(){var t=+this;if(m.hasOwnProperty(t)){var e=m[t];delete m[t],e()}},x=function(t){_.call(t.data)};p&&h||(p=function(t){for(var e=[],r=1;arguments.length>r;)e.push(arguments[r++]);return m[++y]=function(){s("function"==typeof t?t:Function(t),e)},n(y),y},h=function(t){delete m[t]},"process"==r(19)(l)?n=function(t){l.nextTick(a(_,t,1))}:v&&v.now?n=function(t){v.now(a(_,t,1))}:d?(i=(o=new d).port2,o.port1.onmessage=x,n=a(i.postMessage,i,1)):f.addEventListener&&"function"==typeof postMessage&&!f.importScripts?(n=function(t){f.postMessage(t+"","*")},f.addEventListener("message",x,!1)):n="onreadystatechange"in c("script")?function(t){u.appendChild(c("script")).onreadystatechange=function(){u.removeChild(this),_.call(t)}}:function(t){setTimeout(a(_,t,1),0)}),t.exports={set:p,clear:h}},function(t,e){t.exports=function(t){try{return{e:!1,v:t()}}catch(t){return{e:!0,v:t}}}},function(t,e,r){var n=r(6),o=r(9),i=r(26);t.exports=function(t,e){if(n(t),o(e)&&e.constructor===t)return e;var r=i.f(t);return(0,r.resolve)(e),r.promise}},function(t,e,r){t.exports=r(85)},function(t,e,r){var n=r(2),o=r(17),i=r(15),a=r(27),s="["+a+"]",u=RegExp("^"+s+s+"*"),c=RegExp(s+s+"*$"),f=function(t,e,r){var o={},s=i(function(){return!!a[t]()||"​…"!="​…"[t]()}),u=o[t]=s?e(l):a[t];r&&(o[r]=u),n(n.P+n.F*s,"String",o)},l=f.trim=function(t,e){return t=String(o(t)),1&e&&(t=t.replace(u,"")),2&e&&(t=t.replace(c,"")),t};t.exports=f},function(t,e,r){t.exports=r(98)},function(t,e,r){t.exports=r(100)},function(t,e,r){"use strict";(0,r(4)(r(5)).default)(e,"__esModule",{value:!0});var n=r(52),o=r(83),i=r(84),a={Downloader:n.default,Parser:o.default,Player:i.default};e.default=a},function(t,e,r){r(51);var n=r(1).Object;t.exports=function(t,e,r){return n.defineProperty(t,e,r)}},function(t,e,r){var n=r(2);n(n.S+n.F*!r(7),"Object",{defineProperty:r(11).f})},function(t,e,r){"use strict";var n=r(4),o=n(r(16));(0,n(r(5)).default)(e,"__esModule",{value:!0});var i=function(){function t(){}return t.prototype.get=function(t){if(!t)throw new Error("download link undefined");return new o.default(function(e,r){var n=new XMLHttpRequest;n.open("GET",t,!0),n.responseType="arraybuffer",n.onloadend=function(){return e(n.response)},n.onerror=function(){return r(n.response)},n.send()})},t}();e.default=i},function(t,e,r){r(54),r(55),r(65),r(69),r(81),r(82),t.exports=r(1).Promise},function(t,e){},function(t,e,r){"use strict";var n=r(56)(!0);r(31)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,r=this._i;return r>=e.length?{value:void 0,done:!0}:(t=n(e,r),this._i+=t.length,{value:t,done:!1})})},function(t,e,r){var n=r(22),o=r(17);t.exports=function(t){return function(e,r){var i,a,s=String(o(e)),u=n(r),c=s.length;return u<0||u>=c?t?"":void 0:(i=s.charCodeAt(u))<55296||i>56319||u+1===c||(a=s.charCodeAt(u+1))<56320||a>57343?t?s.charAt(u):i:t?s.slice(u,u+2):a-56320+(i-55296<<10)+65536}}},function(t,e,r){t.exports=r(8)},function(t,e,r){"use strict";var n=r(32),o=r(21),i=r(25),a={};r(8)(a,r(3)("iterator"),function(){return this}),t.exports=function(t,e,r){t.prototype=n(a,{next:o(1,r)}),i(t,e+" Iterator")}},function(t,e,r){var n=r(11),o=r(6),i=r(33);t.exports=r(7)?Object.defineProperties:function(t,e){o(t);for(var r,a=i(e),s=a.length,u=0;s>u;)n.f(t,r=a[u++],e[r]);return t}},function(t,e,r){var n=r(12),o=r(18),i=r(62)(!1),a=r(24)("IE_PROTO");t.exports=function(t,e){var r,s=o(t),u=0,c=[];for(r in s)r!=a&&n(s,r)&&c.push(r);for(;e.length>u;)n(s,r=e[u++])&&(~i(c,r)||c.push(r));return c}},function(t,e,r){var n=r(19);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==n(t)?t.split(""):Object(t)}},function(t,e,r){var n=r(18),o=r(34),i=r(63);t.exports=function(t){return function(e,r,a){var s,u=n(e),c=o(u.length),f=i(a,c);if(t&&r!=r){for(;c>f;)if((s=u[f++])!=s)return!0}else for(;c>f;f++)if((t||f in u)&&u[f]===r)return t||f||0;return!t&&-1}}},function(t,e,r){var n=r(22),o=Math.max,i=Math.min;t.exports=function(t,e){return(t=n(t))<0?o(t+e,0):i(t,e)}},function(t,e,r){var n=r(12),o=r(39),i=r(24)("IE_PROTO"),a=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=o(t),n(t,i)?t[i]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?a:null}},function(t,e,r){r(66);for(var n=r(0),o=r(8),i=r(13),a=r(3)("toStringTag"),s="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),u=0;u<s.length;u++){var c=s[u],f=n[c],l=f&&f.prototype;l&&!l[a]&&o(l,a,c),i[c]=i.Array}},function(t,e,r){"use strict";var n=r(67),o=r(68),i=r(13),a=r(18);t.exports=r(31)(Array,"Array",function(t,e){this._t=a(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,r=this._i++;return!t||r>=t.length?(this._t=void 0,o(1)):o(0,"keys"==e?r:"values"==e?t[r]:[r,t[r]])},"values"),i.Arguments=i.Array,n("keys"),n("values"),n("entries")},function(t,e){t.exports=function(){}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,r){"use strict";var n,o,i,a,s=r(23),u=r(0),c=r(10),f=r(40),l=r(2),p=r(9),h=r(14),d=r(70),v=r(71),y=r(41),m=r(42).set,_=r(76)(),x=r(26),b=r(43),g=r(77),w=r(44),S=u.TypeError,k=u.process,O=k&&k.versions,P=O&&O.v8||"",T=u.Promise,F="process"==f(k),E=function(){},j=o=x.f,M=!!function(){try{var t=T.resolve(1),e=(t.constructor={})[r(3)("species")]=function(t){t(E,E)};return(F||"function"==typeof PromiseRejectionEvent)&&t.then(E)instanceof e&&0!==P.indexOf("6.6")&&-1===g.indexOf("Chrome/66")}catch(t){}}(),N=function(t){var e;return!(!p(t)||"function"!=typeof(e=t.then))&&e},R=function(t,e){if(!t._n){t._n=!0;var r=t._c;_(function(){for(var n=t._v,o=1==t._s,i=0,a=function(e){var r,i,a,s=o?e.ok:e.fail,u=e.resolve,c=e.reject,f=e.domain;try{s?(o||(2==t._h&&L(t),t._h=1),!0===s?r=n:(f&&f.enter(),r=s(n),f&&(f.exit(),a=!0)),r===e.promise?c(S("Promise-chain cycle")):(i=N(r))?i.call(r,u,c):u(r)):c(n)}catch(t){f&&!a&&f.exit(),c(t)}};r.length>i;)a(r[i++]);t._c=[],t._n=!1,e&&!t._h&&A(t)})}},A=function(t){m.call(u,function(){var e,r,n,o=t._v,i=C(t);if(i&&(e=b(function(){F?k.emit("unhandledRejection",o,t):(r=u.onunhandledrejection)?r({promise:t,reason:o}):(n=u.console)&&n.error&&n.error("Unhandled promise rejection",o)}),t._h=F||C(t)?2:1),t._a=void 0,i&&e.e)throw e.v})},C=function(t){return 1!==t._h&&0===(t._a||t._c).length},L=function(t){m.call(u,function(){var e;F?k.emit("rejectionHandled",t):(e=u.onrejectionhandled)&&e({promise:t,reason:t._v})})},I=function(t){var e=this;e._d||(e._d=!0,(e=e._w||e)._v=t,e._s=2,e._a||(e._a=e._c.slice()),R(e,!0))},D=function(t){var e,r=this;if(!r._d){r._d=!0,r=r._w||r;try{if(r===t)throw S("Promise can't be resolved itself");(e=N(t))?_(function(){var n={_w:r,_d:!1};try{e.call(t,c(D,n,1),c(I,n,1))}catch(t){I.call(n,t)}}):(r._v=t,r._s=1,R(r,!1))}catch(t){I.call({_w:r,_d:!1},t)}}};M||(T=function(t){d(this,T,"Promise","_h"),h(t),n.call(this);try{t(c(D,this,1),c(I,this,1))}catch(t){I.call(this,t)}},(n=function(t){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1}).prototype=r(78)(T.prototype,{then:function(t,e){var r=j(y(this,T));return r.ok="function"!=typeof t||t,r.fail="function"==typeof e&&e,r.domain=F?k.domain:void 0,this._c.push(r),this._a&&this._a.push(r),this._s&&R(this,!1),r.promise},catch:function(t){return this.then(void 0,t)}}),i=function(){var t=new n;this.promise=t,this.resolve=c(D,t,1),this.reject=c(I,t,1)},x.f=j=function(t){return t===T||t===a?new i(t):o(t)}),l(l.G+l.W+l.F*!M,{Promise:T}),r(25)(T,"Promise"),r(79)("Promise"),a=r(1).Promise,l(l.S+l.F*!M,"Promise",{reject:function(t){var e=j(this);return(0,e.reject)(t),e.promise}}),l(l.S+l.F*(s||!M),"Promise",{resolve:function(t){return w(s&&this===a?T:this,t)}}),l(l.S+l.F*!(M&&r(80)(function(t){T.all(t).catch(E)})),"Promise",{all:function(t){var e=this,r=j(e),n=r.resolve,o=r.reject,i=b(function(){var r=[],i=0,a=1;v(t,!1,function(t){var s=i++,u=!1;r.push(void 0),a++,e.resolve(t).then(function(t){u||(u=!0,r[s]=t,--a||n(r))},o)}),--a||n(r)});return i.e&&o(i.v),r.promise},race:function(t){var e=this,r=j(e),n=r.reject,o=b(function(){v(t,!1,function(t){e.resolve(t).then(r.resolve,n)})});return o.e&&n(o.v),r.promise}})},function(t,e){t.exports=function(t,e,r,n){if(!(t instanceof e)||void 0!==n&&n in t)throw TypeError(r+": incorrect invocation!");return t}},function(t,e,r){var n=r(10),o=r(72),i=r(73),a=r(6),s=r(34),u=r(74),c={},f={};(e=t.exports=function(t,e,r,l,p){var h,d,v,y,m=p?function(){return t}:u(t),_=n(r,l,e?2:1),x=0;if("function"!=typeof m)throw TypeError(t+" is not iterable!");if(i(m)){for(h=s(t.length);h>x;x++)if((y=e?_(a(d=t[x])[0],d[1]):_(t[x]))===c||y===f)return y}else for(v=m.call(t);!(d=v.next()).done;)if((y=o(v,_,d.value,e))===c||y===f)return y}).BREAK=c,e.RETURN=f},function(t,e,r){var n=r(6);t.exports=function(t,e,r,o){try{return o?e(n(r)[0],r[1]):e(r)}catch(e){var i=t.return;throw void 0!==i&&n(i.call(t)),e}}},function(t,e,r){var n=r(13),o=r(3)("iterator"),i=Array.prototype;t.exports=function(t){return void 0!==t&&(n.Array===t||i[o]===t)}},function(t,e,r){var n=r(40),o=r(3)("iterator"),i=r(13);t.exports=r(1).getIteratorMethod=function(t){if(null!=t)return t[o]||t["@@iterator"]||i[n(t)]}},function(t,e){t.exports=function(t,e,r){var n=void 0===r;switch(e.length){case 0:return n?t():t.call(r);case 1:return n?t(e[0]):t.call(r,e[0]);case 2:return n?t(e[0],e[1]):t.call(r,e[0],e[1]);case 3:return n?t(e[0],e[1],e[2]):t.call(r,e[0],e[1],e[2]);case 4:return n?t(e[0],e[1],e[2],e[3]):t.call(r,e[0],e[1],e[2],e[3])}return t.apply(r,e)}},function(t,e,r){var n=r(0),o=r(42).set,i=n.MutationObserver||n.WebKitMutationObserver,a=n.process,s=n.Promise,u="process"==r(19)(a);t.exports=function(){var t,e,r,c=function(){var n,o;for(u&&(n=a.domain)&&n.exit();t;){o=t.fn,t=t.next;try{o()}catch(n){throw t?r():e=void 0,n}}e=void 0,n&&n.enter()};if(u)r=function(){a.nextTick(c)};else if(!i||n.navigator&&n.navigator.standalone)if(s&&s.resolve){var f=s.resolve(void 0);r=function(){f.then(c)}}else r=function(){o.call(n,c)};else{var l=!0,p=document.createTextNode("");new i(c).observe(p,{characterData:!0}),r=function(){p.data=l=!l}}return function(n){var o={fn:n,next:void 0};e&&(e.next=o),t||(t=o,r()),e=o}}},function(t,e,r){var n=r(0).navigator;t.exports=n&&n.userAgent||""},function(t,e,r){var n=r(8);t.exports=function(t,e,r){for(var o in e)r&&t[o]?t[o]=e[o]:n(t,o,e[o]);return t}},function(t,e,r){"use strict";var n=r(0),o=r(1),i=r(11),a=r(7),s=r(3)("species");t.exports=function(t){var e="function"==typeof o[t]?o[t]:n[t];a&&e&&!e[s]&&i.f(e,s,{configurable:!0,get:function(){return this}})}},function(t,e,r){var n=r(3)("iterator"),o=!1;try{var i=[7][n]();i.return=function(){o=!0},Array.from(i,function(){throw 2})}catch(t){}t.exports=function(t,e){if(!e&&!o)return!1;var r=!1;try{var i=[7],a=i[n]();a.next=function(){return{done:r=!0}},i[n]=function(){return a},t(i)}catch(t){}return r}},function(t,e,r){"use strict";var n=r(2),o=r(1),i=r(0),a=r(41),s=r(44);n(n.P+n.R,"Promise",{finally:function(t){var e=a(this,o.Promise||i.Promise),r="function"==typeof t;return this.then(r?function(r){return s(e,t()).then(function(){return r})}:t,r?function(r){return s(e,t()).then(function(){throw r})}:t)}})},function(t,e,r){"use strict";var n=r(2),o=r(26),i=r(43);n(n.S,"Promise",{try:function(t){var e=o.f(this),r=i(t);return(r.e?e.reject:e.resolve)(r.v),e.promise}})},function(module,exports,__webpack_require__){"use strict";var _interopRequireDefault=__webpack_require__(4),_promise=_interopRequireDefault(__webpack_require__(16)),_defineProperty=_interopRequireDefault(__webpack_require__(5));(0,_defineProperty.default)(exports,"__esModule",{value:!0});var WORKER="#INLINE_WROKER#",Parser=function(){function Parser(_a){var disableWorker=(void 0===_a?{disableWorker:!1}:_a).disableWorker;disableWorker?(eval(WORKER),this.worker=window.SVGAMockWorker):this.worker=new Worker(window.URL.createObjectURL(new Blob([WORKER])))}return Parser.prototype.do=function(t){var e=this;if(!t)throw new Error("Parser Data not found");if(!this.worker)throw new Error("Parser Worker not found");return new _promise.default(function(r,n){console.log(e.worker.disableWorker),e.worker.disableWorker?(e.worker.onmessageCallback=function(t){r(t)},e.worker.onmessage({data:t})):(e.worker.postMessage(t),e.worker.onmessage=function(t){var e=t.data;r(e)})})},Parser}();exports.default=Parser},function(t,e,r){"use strict";var n=r(4),o=n(r(45)),i=n(r(16));(0,n(r(5)).default)(e,"__esModule",{value:!0});var a,s,u=r(88),c=r(106);!function(t){t.FORWARDS="forwards",t.BACKWARDS="backwards"}(a||(a={})),function(t){t.FORWARDS="forwards",t.FALLBACKS="fallbacks"}(s||(s={}));var f=function(){function t(t,e,r){if(this.videoItem=e,this.loop=!0,this.fillMode=a.FORWARDS,this.playMode=s.FORWARDS,this.progress=0,this.currentFrame=0,this.totalFramesCount=0,this.startFrame=0,this.endFrame=0,this.$onEvent={start:function(){},process:function(){},pause:function(){},stop:function(){},end:function(){},clear:function(){}},this.container="string"==typeof t?document.body.querySelector(t):t,!this.container)throw new Error("container undefined.");if(!this.container.getContext)throw new Error("container should be HTMLCanvasElement.");this._renderer=new u.default(this),this.videoItem&&this.mount(e)}return t.prototype.set=function(t){void 0!==t.loop&&(this.loop=t.loop),t.fillMode&&(this.fillMode=t.fillMode),t.playMode&&(this.playMode=t.playMode),t.startFrame&&(this.startFrame=t.startFrame),t.endFrame&&(this.endFrame=t.endFrame)},t.prototype.mount=function(t){var e=this;return new i.default(function(r,n){e.currentFrame=0,e.progress=0,e.totalFramesCount=t.frames-1,e.videoItem=t,e._renderer.prepare().then(r),e.clear(),e._setSize()})},t.prototype.start=function(){if(!this.videoItem)throw new Error("video item undefined.");this.clear(),this._startAnimation(),this.$onEvent.start()},t.prototype.pause=function(){this._animator.stop(),this.$onEvent.pause()},t.prototype.stop=function(){this._animator.stop(),this.currentFrame=0,this._renderer.drawFrame(this.currentFrame),this.$onEvent.stop()},t.prototype.clear=function(){this._renderer.clear(),this.$onEvent.clear()},t.prototype.$on=function(t,e){return this.$onEvent[t]=e,this},t.prototype._startAnimation=function(){var t=this;this._animator=new c.default;var e=this.playMode,r=this.totalFramesCount,n=this.startFrame,i=this.endFrame;this._animator.startValue="fallbacks"===e?i||r:n||0,this._animator.endValue="fallbacks"===e?n||0:i||r,this._animator.duration=this.videoItem.frames*(1/this.videoItem.FPS)*1e3,this._animator.loop=!0===this.loop||this.loop<=0?1/0:!1===this.loop?1:this.loop,this._animator.fillRule="backwards"===this.fillMode?1:0,this._animator.onUpdate=function(e){e=Math.floor(e),t.currentFrame!==e&&(t.currentFrame=e,t.progress=(0,o.default)((e+1).toString())/(0,o.default)(t.videoItem.frames.toString())*100,t._renderer.drawFrame(t.currentFrame),t.$onEvent.process())},this._animator.onEnd=function(){return t.$onEvent.end()},this._animator.start(this.currentFrame)},t.prototype._setSize=function(){var t=this.videoItem.videoSize;this.container.width=t.width,this.container.height=t.height},t}();e.default=f},function(t,e,r){r(86),t.exports=r(1).parseFloat},function(t,e,r){var n=r(2),o=r(87);n(n.G+n.F*(parseFloat!=o),{parseFloat:o})},function(t,e,r){var n=r(0).parseFloat,o=r(46).trim;t.exports=1/n(r(27)+"-0")!=-1/0?function(t){var e=o(String(t),3),r=n(e);return 0===r&&"-"==e.charAt(0)?-0:r}:n},function(t,e,r){"use strict";var n=r(4),o=n(r(89)),i=n(r(45)),a=n(r(93)),s=n(r(16));(0,n(r(5)).default)(e,"__esModule",{value:!0});var u=r(28),c=r(97),f=r(105),l=function(){function t(t){this._bitmapCache={},this._dynamicElements={},this._player=t,this._canvasContext=this._player.container.getContext("2d")}return t.prototype.prepare=function(){var t=this;return new s.default(function(e,r){if(t._bitmapCache={},t._player.videoItem.images&&0!=(0,a.default)(t._player.videoItem.images).length){t._dynamicElements=t._player.videoItem.dynamicElements;var n=0,o=0;for(var i in t._player.videoItem.images){var s=t._player.videoItem.images[i];if("string"!=typeof s||0!==s.indexOf("iVBO")&&0!==s.indexOf("/9j/2w"))t._bitmapCache[i]=s;else{n++;var u=document.createElement("img");u.src="data:image/png;base64,"+s,t._bitmapCache[i]=u,u.onload=function(){++o===n&&e()}}}}else e()})},t.prototype.clear=function(){this._canvasContext.clearRect(0,0,this._player.container.width,this._player.container.height)},t.prototype.drawFrame=function(t){var e=this;this.clear();var r=this._canvasContext;this._player.videoItem.sprites.forEach(function(t){var n=t.frames[e._player.currentFrame];if(!(n.alpha<.05)){r.save(),r.globalAlpha=n.alpha,r.transform(n.transform.a,n.transform.b,n.transform.c,n.transform.d,n.transform.tx,n.transform.ty);var o=e._bitmapCache[t.imageKey];o&&(void 0!==n.maskPath&&null!==n.maskPath&&(n.maskPath._styles=void 0,e.drawBezier(n.maskPath),r.clip()),r.drawImage(o,0,0));var a=e._dynamicElements[t.imageKey];a&&r.drawImage(a,(n.layout.width-a.width)/2,(n.layout.height-a.height)/2),n.shapes&&n.shapes.forEach(function(t){"shape"===t.type&&t.pathArgs&&t.pathArgs.d?e.drawBezier(new u.default(t.pathArgs.d,t.transform,t.styles)):"ellipse"===t.type&&t.pathArgs?e._drawEllipse(new c.default((0,i.default)(t.pathArgs.x)||0,(0,i.default)(t.pathArgs.y)||0,(0,i.default)(t.pathArgs.radiusX)||0,(0,i.default)(t.pathArgs.radiusY)||0,t.transform,t.styles)):"rect"===t.type&&t.pathArgs&&e._drawRect(new f.default((0,i.default)(t.pathArgs.x)||0,(0,i.default)(t.pathArgs.y)||0,(0,i.default)(t.pathArgs.width)||0,(0,i.default)(t.pathArgs.height)||0,(0,i.default)(t.pathArgs.cornerRadius)||0,t.transform,t.styles))}),r.restore()}})},t.prototype._resetShapeStyles=function(t){var e=this._canvasContext,r=t._styles;void 0!==r&&(r&&r.stroke?e.strokeStyle="rgba("+(0,o.default)((255*r.stroke[0]).toString())+", "+(0,o.default)((255*r.stroke[1]).toString())+", "+(0,o.default)((255*r.stroke[2]).toString())+", "+r.stroke[3]+")":e.strokeStyle="transparent",r&&(e.lineWidth=r.strokeWidth||void 0,e.lineCap=r.lineCap||void 0,e.lineJoin=r.lineJoin||void 0,e.miterLimit=r.miterLimit||void 0),r&&r.fill?e.fillStyle="rgba("+(0,o.default)((255*r.fill[0]).toString())+", "+(0,o.default)((255*r.fill[1]).toString())+", "+(0,o.default)((255*r.fill[2]).toString())+", "+r.fill[3]+")":e.fillStyle="transparent",r&&r.lineDash&&e.setLineDash(r.lineDash))},t.prototype.drawBezier=function(t){var e=this,r=this._canvasContext;r.save(),this._resetShapeStyles(t),void 0!==t._transform&&null!==t._transform&&r.transform(t._transform.a,t._transform.b,t._transform.c,t._transform.d,t._transform.tx,t._transform.ty);var n={x:0,y:0,x1:0,y1:0,x2:0,y2:0};r.beginPath(),t._d.replace(/([a-zA-Z])/g,"|||$1 ").replace(/,/g," ").split("|||").forEach(function(t){if(0!=t.length){var r=t.substr(0,1);if("MLHVCSQRZmlhvcsqrz".indexOf(r)>=0){var o=t.substr(1).trim().split(" ");e._drawBezierElement(n,r,o)}}}),t._styles&&t._styles.fill?r.fill():t._styles&&t._styles.stroke&&r.stroke(),r.restore()},t.prototype._drawBezierElement=function(t,e,r){var n=this._canvasContext;switch(e){case"M":t.x=Number(r[0]),t.y=Number(r[1]),n.moveTo(t.x,t.y);break;case"m":t.x+=Number(r[0]),t.y+=Number(r[1]),n.moveTo(t.x,t.y);break;case"L":t.x=Number(r[0]),t.y=Number(r[1]),n.lineTo(t.x,t.y);break;case"l":t.x+=Number(r[0]),t.y+=Number(r[1]),n.lineTo(t.x,t.y);break;case"H":t.x=Number(r[0]),n.lineTo(t.x,t.y);break;case"h":t.x+=Number(r[0]),n.lineTo(t.x,t.y);break;case"V":t.y=Number(r[0]),n.lineTo(t.x,t.y);break;case"v":t.y+=Number(r[0]),n.lineTo(t.x,t.y);break;case"C":t.x1=Number(r[0]),t.y1=Number(r[1]),t.x2=Number(r[2]),t.y2=Number(r[3]),t.x=Number(r[4]),t.y=Number(r[5]),n.bezierCurveTo(t.x1,t.y1,t.x2,t.y2,t.x,t.y);break;case"c":t.x1=t.x+Number(r[0]),t.y1=t.y+Number(r[1]),t.x2=t.x+Number(r[2]),t.y2=t.y+Number(r[3]),t.x+=Number(r[4]),t.y+=Number(r[5]),n.bezierCurveTo(t.x1,t.y1,t.x2,t.y2,t.x,t.y);break;case"S":t.x1&&t.y1&&t.x2&&t.y2?(t.x1=t.x-t.x2+t.x,t.y1=t.y-t.y2+t.y,t.x2=Number(r[0]),t.y2=Number(r[1]),t.x=Number(r[2]),t.y=Number(r[3]),n.bezierCurveTo(t.x1,t.y1,t.x2,t.y2,t.x,t.y)):(t.x1=Number(r[0]),t.y1=Number(r[1]),t.x=Number(r[2]),t.y=Number(r[3]),n.quadraticCurveTo(t.x1,t.y1,t.x,t.y));break;case"s":t.x1&&t.y1&&t.x2&&t.y2?(t.x1=t.x-t.x2+t.x,t.y1=t.y-t.y2+t.y,t.x2=t.x+Number(r[0]),t.y2=t.y+Number(r[1]),t.x+=Number(r[2]),t.y+=Number(r[3]),n.bezierCurveTo(t.x1,t.y1,t.x2,t.y2,t.x,t.y)):(t.x1=t.x+Number(r[0]),t.y1=t.y+Number(r[1]),t.x+=Number(r[2]),t.y+=Number(r[3]),n.quadraticCurveTo(t.x1,t.y1,t.x,t.y));break;case"Q":t.x1=Number(r[0]),t.y1=Number(r[1]),t.x=Number(r[2]),t.y=Number(r[3]),n.quadraticCurveTo(t.x1,t.y1,t.x,t.y);break;case"q":t.x1=t.x+Number(r[0]),t.y1=t.y+Number(r[1]),t.x+=Number(r[2]),t.y+=Number(r[3]),n.quadraticCurveTo(t.x1,t.y1,t.x,t.y);break;case"A":case"a":break;case"Z":case"z":n.closePath()}},t.prototype._drawEllipse=function(t){var e=this._canvasContext;e.save(),this._resetShapeStyles(t),void 0!==t._transform&&null!==t._transform&&e.transform(t._transform.a,t._transform.b,t._transform.c,t._transform.d,t._transform.tx,t._transform.ty);var r=t._x-t._radiusX,n=t._y-t._radiusY,o=2*t._radiusX,i=2*t._radiusY,a=o/2*.5522848,s=i/2*.5522848,u=r+o,c=n+i,f=r+o/2,l=n+i/2;e.beginPath(),e.moveTo(r,l),e.bezierCurveTo(r,l-s,f-a,n,f,n),e.bezierCurveTo(f+a,n,u,l-s,u,l),e.bezierCurveTo(u,l+s,f+a,c,f,c),e.bezierCurveTo(f-a,c,r,l+s,r,l),t._styles&&t._styles.fill?e.fill():t._styles&&t._styles.stroke&&e.stroke(),e.restore()},t.prototype._drawRect=function(t){var e=this._canvasContext;e.save(),this._resetShapeStyles(t),void 0!==t._transform&&null!==t._transform&&e.transform(t._transform.a,t._transform.b,t._transform.c,t._transform.d,t._transform.tx,t._transform.ty);var r=t._x,n=t._y,o=t._width,i=t._height,a=t._cornerRadius;o<2*a&&(a=o/2),i<2*a&&(a=i/2),e.beginPath(),e.moveTo(r+a,n),e.arcTo(r+o,n,r+o,n+i,a),e.arcTo(r+o,n+i,r,n+i,a),e.arcTo(r,n+i,r,n,a),e.arcTo(r,n,r+o,n,a),e.closePath(),t._styles&&t._styles.fill?e.fill():t._styles&&t._styles.stroke&&e.stroke(),e.restore()},t}();e.default=l},function(t,e,r){t.exports=r(90)},function(t,e,r){r(91),t.exports=r(1).parseInt},function(t,e,r){var n=r(2),o=r(92);n(n.G+n.F*(parseInt!=o),{parseInt:o})},function(t,e,r){var n=r(0).parseInt,o=r(46).trim,i=r(27),a=/^[-+]?0[xX]/;t.exports=8!==n(i+"08")||22!==n(i+"0x16")?function(t,e){var r=o(String(t),3);return n(r,e>>>0||(a.test(r)?16:10))}:n},function(t,e,r){t.exports=r(94)},function(t,e,r){r(95),t.exports=r(1).Object.keys},function(t,e,r){var n=r(39),o=r(33);r(96)("keys",function(){return function(t){return o(n(t))}})},function(t,e,r){var n=r(2),o=r(1),i=r(15);t.exports=function(t,e){var r=(o.Object||{})[t]||Object[t],a={};a[t]=e(r),n(n.S+n.F*i(function(){r(1)}),"Object",a)}},function(t,e,r){"use strict";var n,o=r(4),i=o(r(5)),a=o(r(47)),s=o(r(48)),u=(n=function(t,e){return(n=s.default||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])})(t,e)},function(t,e){function r(){this.constructor=t}n(t,e),t.prototype=null===e?(0,a.default)(e):(r.prototype=e.prototype,new r)});(0,i.default)(e,"__esModule",{value:!0});var c=function(t){function e(e,r,n,o,i,a){var s=t.call(this)||this;return s._x=e,s._y=r,s._radiusX=n,s._radiusY=o,s._transform=i,s._styles=a,s}return u(e,t),e}(r(28).default);e.default=c},function(t,e,r){r(99);var n=r(1).Object;t.exports=function(t,e){return n.create(t,e)}},function(t,e,r){var n=r(2);n(n.S,"Object",{create:r(32)})},function(t,e,r){r(101),t.exports=r(1).Object.setPrototypeOf},function(t,e,r){var n=r(2);n(n.S,"Object",{setPrototypeOf:r(102).set})},function(t,e,r){var n=r(9),o=r(6),i=function(t,e){if(o(t),!n(e)&&null!==e)throw TypeError(e+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(t,e,n){try{(n=r(10)(Function.call,r(103).f(Object.prototype,"__proto__").set,2))(t,[]),e=!(t instanceof Array)}catch(t){e=!0}return function(t,r){return i(t,r),e?t.__proto__=r:n(t,r),t}}({},!1):void 0),check:i}},function(t,e,r){var n=r(104),o=r(21),i=r(18),a=r(30),s=r(12),u=r(29),c=Object.getOwnPropertyDescriptor;e.f=r(7)?c:function(t,e){if(t=i(t),e=a(e,!0),u)try{return c(t,e)}catch(t){}if(s(t,e))return o(!n.f.call(t,e),t[e])}},function(t,e){e.f={}.propertyIsEnumerable},function(t,e,r){"use strict";var n,o=r(4),i=o(r(5)),a=o(r(47)),s=o(r(48)),u=(n=function(t,e){return(n=s.default||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])})(t,e)},function(t,e){function r(){this.constructor=t}n(t,e),t.prototype=null===e?(0,a.default)(e):(r.prototype=e.prototype,new r)});(0,i.default)(e,"__esModule",{value:!0});var c=function(t){function e(e,r,n,o,i,a,s){var u=t.call(this)||this;return u._x=e,u._y=r,u._width=n,u._height=o,u._cornerRadius=i,u._transform=a,u._styles=s,u}return u(e,t),e}(r(28).default);e.default=c},function(t,e,r){"use strict";var n=r(4)(r(5));(0,n.default)(e,"__esModule",{value:!0});var o=function(){function t(){this.startValue=0,this.endValue=0,this.duration=0,this.loop=1,this.fillRule=0,this.onStart=function(){},this.onUpdate=function(){},this.onEnd=function(){},this._isRunning=!1,this._mStartTime=0,this._currentFrication=0}return t.prototype.start=function(t){this.doStart(t)},t.prototype.stop=function(){this._doStop()},(0,n.default)(t.prototype,"animatedValue",{get:function(){return(this.endValue-this.startValue)*this._currentFrication+this.startValue},enumerable:!0,configurable:!0}),t.prototype.doStart=function(e){this._isRunning=!0,this._mStartTime=t._currentTimeMillsecond(),e&&(this._mStartTime-=e/(this.endValue-this.startValue)*this.duration),this._currentFrication=0,this.onStart(),this._doFrame()},t.prototype._doStop=function(){this._isRunning=!1},t.prototype._doFrame=function(){this._isRunning&&(this._doDeltaTime(t._currentTimeMillsecond()-this._mStartTime),this._isRunning&&t._requestAnimationFrame(this._doFrame.bind(this)))},t.prototype._doDeltaTime=function(t){t>=this.duration*this.loop?(this._currentFrication=1===this.fillRule?0:1,this._isRunning=!1):this._currentFrication=t%this.duration/this.duration,this.onUpdate(this.animatedValue),!1===this._isRunning&&this.onEnd()},t._currentTimeMillsecond=function(){return"undefined"==typeof performance?(new Date).getTime():performance.now()},t._requestAnimationFrame=function(t){t&&setTimeout(t,16)},t}();e.default=o}]).default});
\ No newline at end of file
<html>
<body style="text-align: center">
<div>
<canvas id="drawingCanvas" width="500" height="1000" style="background-color: #000000; "></canvas>
</div>
<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>
<script src="../build/svga.min.js"></script>
<script>
var parser = new SVGA.Parser()
var player = new SVGA.Player()
parser.load("./samples/rose.svga", function (videoItem) {
player.setVideoItem(videoItem);
player.startAnimation()
})
const requestFrame = () => {
requestAnimationFrame(() => {
const ctx = document.getElementById('drawingCanvas').getContext('2d');
ctx.clearRect(0, 0, 500, 1000);
ctx.fillStyle = "#e2e2e2"
ctx.fillRect(0, 0, 500, 1000);
player.drawOnContext(ctx, 100, 100, 250, 250);
requestFrame()
})
}
requestFrame();
</script>
</body>
</html>
\ No newline at end of file
# SVGA-Samples
以下动画版权归 YY Inc. 所有,仅用于学习使用,禁止商业使用。
* angel.svga
* halloween.svga
* kingset.svga
* posche.svga
* rose.svga
var path = require('path');
var webpack = require('webpack')
module.exports = {
entry: {
"svga.min": "./src/Canvas/index.js",
"svga.egret.min":"./src/Egret/index.js",
},
output: {
path: __dirname,
filename: "build/[name].js",
libraryTarget: 'umd',
library: 'SVGA',
},
module: {
loaders: [
{
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 },
})
],
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment