Commit af54c1ea authored by 李维's avatar 李维

dev commit

parent 8a51c964
...@@ -9,7 +9,6 @@ ...@@ -9,7 +9,6 @@
# dependencies # dependencies
/node_modules /node_modules
/publish
# profiling files # profiling files
chrome-profiler-events*.json chrome-profiler-events*.json
......
# ng-template-generator # ng-template-generator
angularjs技术框架下的H5互动模板框架脚手架,基于NG-ZORRO实现快速开发基于绘玩云的H5互动课件。 angularjs技术框架下的H5互动模板框架脚手架
\ No newline at end of file
# 使用简介
## 前期准备
* git下载 https://git-scm.com/downloads
* nodejs下载 https://nodejs.org/zh-cn/download/
* 谷歌浏览器下载 https://www.google.cn/chrome/
都下载最新版就行,然后默认安装就可以
## 生成项目
* 登录绘玩云课件开发平台:http://staging-teach.ireadabc.com/
* 点击“登录账号,查看我的课件”
* 输入测试的用户名/密码:developers/12345678
* 在右上角“个人中心”的下拉菜单里,点击“我的模板” 菜单,然后点击“新建模板”, 填写必要的信息,在“技术选型”一项上选择“Angular”
* 点击“确定”后,列表页就会出现一个新生成的模板项目
* 在项目的卡片下找到“开发”按钮,则会弹出相对应的git地址
## 获取并启动项目
```
// xxx 是上面项目对应的Git地址
git clone xxx
cd 项目名称/
npm install -g yarn
yarn install
npm start
//启动成功后打开浏览器,输入:http://localhost:4200 则可以看到这个项目的初始化效果了
```
## 项目结构
|-- bin
|-- dist
|-- e2e
|-- node_modules
|-- publish
|-- src
| |-- app
| | |-- common
| | |-- form
| | |-- pipes
| | |-- play
| | |-- services
| | |-- style
| | |-- app.component.html
| | |-- app.component.scss
| | |-- app.component.ts
| | |-- app.module.ts
| |-- assets
| |-- environments
| |-- services
| |-- index.html
| |-- main.ts
| |--.......
* 其中 play 文件夹是H5模板展示页面,form文件夹是模板的配置页面
* common文件夹是以往做过的模板积累的一些比较常用的 AngularJs 的组件
* assets文件夹存放模板样式的静态资源,例如小图标、背景图片、字体、样式等等
* 其他文件夹开发者可以不做任何更改
## 开始开发
本脚手架的页面类UI框架是基于 [NG-ZORRO](https://ng.ant.design/docs/introduce/zh "With a Title") 框架实现的,在配置页面(form文件夹),一些表单输入,上传图片等组件也可以使用 NG-ZORRO 现成的组件
### 开发配置页面(form/)
配置页面主要作用是为了呈现多样化模板,提高H5模板的高复用性、灵活性提供的一个配置工具,根据H5模板的设计规划或特性,会规定某些元素是可以配置的,比如背景图片、音频、选项、标题等等等等。(课件制作者) 通过配置页面,就可以灵活的更换这些,从而形成多种多样的课件。
配置页面的开发要求很简单,我们不关心布局、样式、交互等所有实现细节与效果,只需调用两个内置的全局接口即可:
* setData 接口,用于将配置的数据存储到云端。
此方法是一个异步的方法,接收三个必要参数
obj: 一个json对象
callback: 回调函数
t_name: 模板名称
一般使用例子如下:
```
// ts语法,不能直接使用js的window对象自定义方法
(<any> window).courseware.setData(obj, callback, t_name);
```
* getData 接口,用于当点击修改的时候将配置的数据从云端获取下来。
此方法是一个异步的方法,接收两个必要参数
> callback: 回调函数, 回调函数里会得到云端保存的数据
> t_name: 模板名称
一般使用例子如下:
```
// ts语法,不能直接使用js的window对象自定义方法
const getData = (<any> window).courseware.getData;
getData((data) => {
//data 就是云端获取的数据,也就是setData方法存到云端的那个obj
//模板开发者需要根据数据,依次填写到表单的相应位置,方便用户二次修改编辑
});
```
### 开发展示页面(play/)
展示页面主要是呈现模板,通过H5技术,实现多样化的交互与展示方式。
展示页面更简单,开发者可以运用各种技术,实现Web端可以实现的任何效果,包括2D、3D、动画、游戏等各种场景,把表单配置的数据获取到,用于渲染相对应的页面即可:
* getData 接口,用于当点击修改的时候将配置的数据从云端获取下来。
此方法是一个异步的方法,接收两个必要参数
> callback: 回调函数, 回调函数里会得到云端保存的数据
> t_name: 模板名称
一般使用例子如下:
```
// ts语法,不能直接使用js的window对象自定义方法
const getData = (<any> window).courseware.getData;
getData((data) => {
//data 就是云端获取的数据,也就是setData方法存到云端的那个obj
//模板开发者需要根据数据来渲染或控制展示页面的呈现,达到模板的互动目的
});
```
### 互动课件
通过H5的交互方式,我们可以很轻松的制作在线的互动课件,使老师端与学生端实现联动,使在线课堂更具有交互性。
* onEvent 定义事件:用于自定义同步事件,配合多端互动使用,与sendEvent方法配合使用,用于监听多端发送的同步事件
参数
> evtName : 自定义事件的名称
> callback : 回调函数,回调函数里会得到传过来的数据
使用例子:
```
const cw = (<any> window).courseware;
//订阅一个事件
cw.onEvent('testEvent', (data,next) => {
console.log(data);
//处理事件的同步逻辑
//在逻辑处理完之后一定要执行next方法,用于解锁事件队列
next();
});
```
* sendEvent 发送事件:用于自定义同步事件,配合多端互动使用,与onEvent方法配合使用,用于对端发送同步事件
参数
> evtName : 自定义事件的名称
> data : 传递的参数
使用例子:
```
const cw = (<any> window).courseware;
//发送事件
//这样,所有端(教师、学生) 都会触发 testEvent 方法
cw.sendEvent('testEvent', 'Hello world');
```
* storeAspect 存储切面数据: 课件的切面状态数据;互动课件需要每一个开发者设计切面状态,用于学生进入已经进行的课件,恢复课件同步。例如老师讲图片轮播到第四页,这个时候学生进入教师,要恢复到第四页,才能跟老师同步上课。
参数
> data : 保存的数据,一个JSON对象
使用例子:
```
const cw = (<any> window).courseware;
//存储切面数据,用于学生进入教室,同步课堂信息等
cw.storeAspect({page: 5});
```
* getAspect 获取切面数据: 课件的切面状态数据;互动课件需要每一个开发者设计切面状态,用于学生进入已经进行的课件,恢复课件同步。例如老师讲图片轮播到第四页,这个时候学生进入教师,要恢复到第四页,才能跟老师同步上课。
参数
> callback : 获取切面数据的回调函数
使用例子:
```
const cw = (<any> window).courseware;
//存储切面数据,用于学生进入教室,同步课堂信息等
cw.getAspect(function(aspect){
//恢复切面状态的逻辑
});
```
* 补充项
1) 有时候我们在实现模板效果的时候,需要一些基本的信息,比如教室信息、当前用户信息等等,例如,老师会显示某个按钮,而学生不显示,我们可以用如下方式获取教室信息;后续大部分静态信息都会完善到这个对象里
```
//获取教室信息,值得注意的是获取这个信息一定要再 getData方法之后,或者确保页面完成之后
getData((data, aspect) => {
let airClassInfo = window["air"].airClassInfo;
console.log(airClassInfo);
});
```
2) 互动课件的 getData 方法的回调函数里多返回了一个切面参数,类似如下:
```
const getData = (<any> window).courseware.getData;
getData((data, aspect) => {
//data 就是云端获取的数据,也就是setData方法存到云端的那个obj
//aspect 切面参数,用于恢复页面的状态
//模板开发者需要根据数据来渲染或控制展示页面的呈现,达到模板的互动目的
});
```
3) 一些必要的内置事件,通过监听这些事件,我们可以实现一些相关的功能
* userchange 事件,用来监听教室内部的人员变动情况,例如某人进入,某人退出都会触发此事件
示例:
```
const cw = (<any> window).courseware;
//订阅一个事件
cw.onEvent('userchange', (data,next) => {
//data的结构如下
/*{
* id: '变动用户的ID',
* connected: true/false, true: 连接的,false:d断开的
* status: 'connect/reconnect', connect:新建连接,reconnect:重新连接;这个字段在断开连接的事件里是缺失的
* all_user: [] 这个是现有的用户列表
*}
*/
console.log(data);
//处理事件的同步逻辑
//在逻辑处理完之后一定要执行next方法,用于解锁事件队列
next();
});
```
4) 测试互动课件
我们在本地开发中,无法模拟线上老师和学生互动的交互场景,所以提供了一套开发者测试的账号,如下:
测试地址:http://staging-ac.ireadabc.com/
老师用户名/密码:devtea / 1
学生用户名/密码: 学生1(13877777711 / 1) 学生2(13877777712 / 1)
测试方法:
1、首先开发者发布完模板之后,在制作课件的菜单下用这个模板制作一个课件
2、在本地打开两个浏览器窗口 一个登陆老师用户,另一个登陆学生用户
3、老师用户进去之后,就会有很多课件,这个时候双击自己制作的课件,学生的窗口就会同步的打开课件了
4、测试自己的交互事件,看看老师端和学生端是否是自己想要的展示效果
### 补充方法
在模板的编辑或展示过程中,还会经常遇到如下两个场景,特提供针对性的解决办法
1) 表单录入往往需要上传图片、音视频等多媒体文件,所以脚手架内置如下方法,用于获取一个上传到云端的接口方法
```
const uploadUrl = (<any> window).courseware.uploadUrl;
const uploadData = (<any> window).courseware.uploadData;
//例如用于NG-ZORRO的上传组件则如下写法:
<nz-upload class="p-image-uploader" [nzDisabled]="disableUpload"
[nzShowUploadList]="false"
nzAccept = "image/*"
[nzAction]="uploadUrl" <!-- 注意这里 -->
[nzData]="uploadData" <!-- 注意这里 -->
(nzChange)="handleChange($event)">
</nz-upload>
```
2) 在展示页面加载完成的时候,需要调用一下下面的方法,用于释放切换课件的遮罩层
```
//此方法为固定写法,
//其中t_name为模板名称,obj是云端存储的配置数据
window["air"].hideAirClassLoading(t_name,obj);
```
## 打包发布
模板开发完成之后,要推送到云平台上使用则需要进行打包发布操作
```
npm run publish
```
在项目根目录下执行上述命令,则在 ./publish 目录下生产一个 .zip的压缩包,此时打开云平台
http://staging-teach.ireadabc.com/
点击“模板管理” 菜单,找到对应的模板卡片,点击“发布”按钮,在弹出的对话框中选中压缩包,然后点击“确定”,上传完成后,则发布就成功了
\ No newline at end of file
...@@ -3,9 +3,13 @@ ...@@ -3,9 +3,13 @@
"version": 1, "version": 1,
"newProjectRoot": "projects", "newProjectRoot": "projects",
"projects": { "projects": {
"ng-template-generator": { "ng-one": {
"projectType": "application", "projectType": "application",
"schematics": {}, "schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "", "root": "",
"sourceRoot": "src", "sourceRoot": "src",
"prefix": "app", "prefix": "app",
...@@ -13,26 +17,39 @@ ...@@ -13,26 +17,39 @@
"build": { "build": {
"builder": "@angular-devkit/build-angular:browser", "builder": "@angular-devkit/build-angular:browser",
"options": { "options": {
"outputPath": "dist/ng-template-generator", "outputPath": "dist",
"index": "src/index.html", "index": "src/index.html",
"main": "src/main.ts", "main": "src/main.ts",
"polyfills": "src/polyfills.ts", "polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json", "tsConfig": "tsconfig.app.json",
"aot": true, "aot": false,
"assets": [ "assets": [
"src/favicon.ico", "src/favicon.ico",
"src/assets", "src/assets",
{ "glob": "**/*", "input": "src/assets/play/libs/service-worker/", "output": "/" },
{ {
"glob": "**/*", "glob": "**/*",
"input": "./node_modules/@ant-design/icons-angular/src/inline-svg/", "input": "./node_modules/@ant-design/icons-angular/src/inline-svg/",
"output": "/assets/" "output": "/assets/"
},
{
"glob": "**/*",
"input": "./dist/game/",
"output": "/assets/cocos/"
} }
], ],
"styles": [ "styles": [
"src/styles.scss",
"./node_modules/ng-zorro-antd/ng-zorro-antd.min.css", "./node_modules/ng-zorro-antd/ng-zorro-antd.min.css",
"src/styles.css" "./node_modules/font-awesome/css/font-awesome.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css",
"./node_modules/animate.css/animate.min.css"
], ],
"scripts": [] "scripts": [
"src/assets/play/libs/audio-recorder/lame.min.js",
"src/assets/play/libs/audio-recorder/worker.js",
"src/assets/play/libs/audio-recorder/recorder.js"
]
}, },
"configurations": { "configurations": {
"production": { "production": {
...@@ -47,39 +64,28 @@ ...@@ -47,39 +64,28 @@
"sourceMap": false, "sourceMap": false,
"extractCss": true, "extractCss": true,
"namedChunks": false, "namedChunks": false,
"aot": true,
"extractLicenses": true, "extractLicenses": true,
"vendorChunk": false, "vendorChunk": false,
"buildOptimizer": true, "buildOptimizer": true
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
} }
} }
}, },
"serve": { "serve": {
"builder": "@angular-devkit/build-angular:dev-server", "builder": "@angular-devkit/build-angular:dev-server",
"options": { "options": {
"browserTarget": "ng-template-generator:build" "browserTarget": "ng-one:build"
}, },
"configurations": { "configurations": {
"production": { "production": {
"browserTarget": "ng-template-generator:build:production" "browserTarget": "ng-one:build:production"
} }
} }
}, },
"extract-i18n": { "extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n", "builder": "@angular-devkit/build-angular:extract-i18n",
"options": { "options": {
"browserTarget": "ng-template-generator:build" "browserTarget": "ng-one:build"
} }
}, },
"test": { "test": {
...@@ -94,8 +100,7 @@ ...@@ -94,8 +100,7 @@
"src/assets" "src/assets"
], ],
"styles": [ "styles": [
"./node_modules/ng-zorro-antd/ng-zorro-antd.min.css", "src/styles.scss"
"src/styles.css"
], ],
"scripts": [] "scripts": []
} }
...@@ -117,16 +122,15 @@ ...@@ -117,16 +122,15 @@
"builder": "@angular-devkit/build-angular:protractor", "builder": "@angular-devkit/build-angular:protractor",
"options": { "options": {
"protractorConfig": "e2e/protractor.conf.js", "protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "ng-template-generator:serve" "devServerTarget": "ng-one:serve"
}, },
"configurations": { "configurations": {
"production": { "production": {
"devServerTarget": "ng-template-generator:serve:production" "devServerTarget": "ng-one:serve:production"
} }
} }
} }
} }
} }},
}, "defaultProject": "ng-one"
"defaultProject": "ng-template-generator" }
} \ No newline at end of file
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* 运行 npm run publish T_01,T_02,T_03,T_04 命令来分别打包 T_01,T_02,T_03,T_04 这四个模板,注意逗号要用英文的 * 运行 npm run publish T_01,T_02,T_03,T_04 命令来分别打包 T_01,T_02,T_03,T_04 这四个模板,注意逗号要用英文的
* 运行 npm run publish all 命令来打包所有模板 * 运行 npm run publish all 命令来打包所有模板
*/ */
const spawn = require('child_process').spawn; const spawn = require('child_process').spawn;
const path = require("path"); const path = require("path");
const fs = require("fs"); const fs = require("fs");
...@@ -12,9 +12,9 @@ const os = require('os'); ...@@ -12,9 +12,9 @@ const os = require('os');
const compressing = require("compressing"); const compressing = require("compressing");
//Linux系统上'Linux' //Linux系统上'Linux'
//macOS 系统上'Darwin' //macOS 系统上'Darwin'
//Windows系统上'Windows_NT' //Windows系统上'Windows_NT'
let sysType = os.type(); let sysType = os.type();
Date.prototype.Format = function(fmt) { Date.prototype.Format = function(fmt) {
var o = { var o = {
...@@ -44,9 +44,9 @@ const runSpawn = async function (){ ...@@ -44,9 +44,9 @@ const runSpawn = async function (){
await new Promise(function(resolve,reject){ await new Promise(function(resolve,reject){
let pkg = require("../package.json"); let pkg = require("../package.json");
let ls; let ls;
if(sysType==="Windows_NT"){ if(sysType==="Windows_NT"){
//ng build --prod --build--optimizer --base-href /ng-one/ //ng build --prod --build--optimizer --base-href /ng-one/
ls = spawn("cmd.exe", ['/c', 'ng', 'build', '--prod', '--build--optimizer', '--base-href', '/template-base-href/'] ); ls = spawn("cmd.exe", ['/c', 'ng', 'build', '--prod', '--build--optimizer', '--base-href', '/template-base-href/'] );
...@@ -57,7 +57,7 @@ const runSpawn = async function (){ ...@@ -57,7 +57,7 @@ const runSpawn = async function (){
ls.stdout.on('data', (data) => { ls.stdout.on('data', (data) => {
console.log(` ${data}`); console.log(` ${data}`);
}); });
ls.stderr.on('data', (data) => { ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`); console.log(`stderr: ${data}`);
reject(); reject();
...@@ -66,13 +66,13 @@ const runSpawn = async function (){ ...@@ -66,13 +66,13 @@ const runSpawn = async function (){
ls.on('close', (code) => { ls.on('close', (code) => {
console.log(`child process exited with code ${code}`); console.log(`child process exited with code ${code}`);
//要压缩的目录 //要压缩的目录
let zippath = path.resolve(__dirname,"../dist", pkg.name); let zippath = path.resolve(__dirname,"../dist");
//压缩包的存放目录 //压缩包的存放目录
let date = new Date(); let date = new Date();
let zipname = pkg.name+"_"+date.Format("yyyyMMdd hh-mm-ss"); let zipname = pkg.name+"_"+date.Format("yyyyMMdd hh-mm-ss");
let zipdir = path.resolve(__dirname,"../publish/"+zipname+".zip"); let zipdir = path.resolve(__dirname,"../publish/"+zipname+".zip");
clean(zipdir); //删除原有的包 clean(zipdir); //删除原有的包
const tarStream = new compressing.zip.Stream(); const tarStream = new compressing.zip.Stream();
fs.readdir(zippath,function(err,files){ fs.readdir(zippath,function(err,files){
if(err){ if(err){
...@@ -84,16 +84,16 @@ const runSpawn = async function (){ ...@@ -84,16 +84,16 @@ const runSpawn = async function (){
tarStream.addEntry(zippath+"/"+files[i]); tarStream.addEntry(zippath+"/"+files[i]);
} }
let writeStream = fs.createWriteStream(zipdir); let writeStream = fs.createWriteStream(zipdir);
tarStream.pipe(writeStream); tarStream.pipe(writeStream);
writeStream.on('close', () => { writeStream.on('close', () => {
console.log(`模板 ${pkg.name} 打包已完成!`); console.log(`模板 ${pkg.name} 打包已完成!`);
resolve(); resolve();
}) })
}); });
}); });
}); });
} }
// let projects = ""; // let projects = "";
...@@ -101,7 +101,7 @@ const runSpawn = async function (){ ...@@ -101,7 +101,7 @@ const runSpawn = async function (){
// console.log("缺少参数"); // console.log("缺少参数");
// return; // return;
// } // }
// projects = process.argv[2]; // projects = process.argv[2];
let exec = async function(){ let exec = async function(){
//压缩模板 //压缩模板
...@@ -110,5 +110,6 @@ let exec = async function(){ ...@@ -110,5 +110,6 @@ let exec = async function(){
exec(); exec();
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -2,56 +2,77 @@ ...@@ -2,56 +2,77 @@
"name": "ng-template-generator", "name": "ng-template-generator",
"version": "0.0.1", "version": "0.0.1",
"scripts": { "scripts": {
"start": "ng serve", "start": "ng serve --host=0.0.0.0",
"build": "ng build --build--optimizer --aot --base-href /JGT/v3/", "build": "ng build --build--optimizer --aot --base-href /JGT/v3/",
"publish": "node ./bin/publish.js", "publish": "node ./bin/publish.js"
"ng": "ng",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
}, },
"private": true, "private": true,
"dependencies": { "dependencies": {
"@angular/animations": "~9.0.2", "@angular/animations": "^7.2.10",
"@angular/common": "~9.0.2", "@angular/cdk": "^7.2.2",
"@angular/compiler": "~9.0.2", "@angular/common": "^7.2.10",
"@angular/core": "~9.0.2", "@angular/compiler": "^7.2.10",
"@angular/forms": "~9.0.2", "@angular/core": "^7.2.10",
"@angular/platform-browser": "~9.0.2", "@angular/flex-layout": "^7.0.0-beta.24",
"@angular/platform-browser-dynamic": "~9.0.2", "@angular/forms": "^7.2.10",
"@angular/router": "~9.0.2", "@angular/http": "^7.2.10",
"@fortawesome/angular-fontawesome": "^0.6.0", "@angular/material": "^7.2.2",
"@fortawesome/fontawesome-svg-core": "^1.2.27", "@angular/platform-browser": "^7.2.10",
"@fortawesome/free-regular-svg-icons": "^5.12.1", "@angular/platform-browser-dynamic": "^7.2.10",
"@fortawesome/free-solid-svg-icons": "^5.12.1", "@angular/platform-server": "^7.2.10",
"@tweenjs/tween.js": "~18.5.0", "@angular/router": "^7.2.10",
"ali-oss": "^6.5.1", "@tweenjs/tween.js": "^17.3.0",
"compressing": "^1.5.0", "ali-oss": "^6.0.0",
"ng-zorro-antd": "^8.5.2", "angular-bootstrap-colorpicker": "^3.0.32",
"rxjs": "~6.5.4", "angular-cropperjs": "^1.0.1",
"angular2-draggable": "^2.1.9",
"angular2-fontawesome": "^5.2.1",
"angular2-uuid": "^1.1.1",
"angularx-qrcode": "^1.5.3",
"animate.css": "^3.7.0",
"bootstrap": "^4.1.1",
"browser-image-compression": "^1.0.5",
"compressing": "^1.4.0",
"core-js": "^2.6.1",
"cropperjs": "1.4.1",
"css-element-queries": "^1.0.2",
"decimal.js": "^10.0.1",
"font-awesome": "^4.7.0",
"hammerjs": "^2.0.8",
"install": "^0.12.2",
"karma-cli": "^2.0.0",
"lodash": "^4.17.10",
"nedb": "^1.8.0",
"ng-lottie": "^0.3.1",
"ng-zorro-antd": "^7.2.0",
"ngx-color-picker": "^9.0.0",
"node-sass": "^4.14.0",
"npm": "^6.5.0",
"rxjs": "^6.3.3",
"rxjs-compat": "^6.3.3",
"rxjs-tslint": "^0.1.6",
"spark-md5": "^3.0.0", "spark-md5": "^3.0.0",
"tslib": "^1.10.0", "webpack": "^4.28.2",
"zone.js": "~0.10.2" "zone.js": "^0.8.26"
}, },
"devDependencies": { "devDependencies": {
"@angular-devkit/build-angular": "~0.900.3", "@angular-devkit/build-angular": "^0.11.4",
"@angular/cli": "~9.0.3", "@angular/cli": "^7.2.10",
"@angular/compiler-cli": "~9.0.2", "@angular/compiler-cli": "^7.2.10",
"@angular/language-service": "~9.0.2", "@angular/language-service": "^7.2.10",
"@types/jasmine": "~3.5.0", "@types/jasmine": "^3.3.5",
"@types/jasminewd2": "~2.0.3", "@types/jasminewd2": "~2.0.3",
"@types/node": "^12.11.1", "@types/node": "^10.12.18",
"codelyzer": "^5.1.2", "codelyzer": "^4.5.0",
"jasmine-core": "~3.5.0", "jasmine-core": "^3.3.0",
"jasmine-spec-reporter": "~4.2.1", "jasmine-spec-reporter": "^4.2.1",
"karma": "~4.3.0", "karma": "^3.1.4",
"karma-chrome-launcher": "~3.1.0", "karma-chrome-launcher": "^2.2.0",
"karma-coverage-istanbul-reporter": "~2.1.0", "karma-coverage-istanbul-reporter": "~2.0.0",
"karma-jasmine": "~2.0.1", "karma-jasmine": "^2.0.1",
"karma-jasmine-html-reporter": "^1.4.2", "karma-jasmine-html-reporter": "^1.4.0",
"protractor": "~5.4.3", "protractor": "^5.4.2",
"ts-node": "~8.3.0", "ts-node": "~5.0.1",
"tslint": "~5.18.0", "typescript": "3.1.1"
"typescript": "~3.7.5"
} }
} }
import { ErrorHandler } from '@angular/core';
export class MyErrorHandler implements ErrorHandler {
handleError(error) {
console.log(error.stack);
(<any> window).courseware.sendErrorLog(error);
}
}
\ No newline at end of file
...@@ -5,12 +5,12 @@ import { Component , OnInit} from '@angular/core'; ...@@ -5,12 +5,12 @@ import { Component , OnInit} from '@angular/core';
templateUrl: './app.component.html', templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'] styleUrls: ['./app.component.scss']
}) })
export class AppComponent implements OnInit { export class AppComponent implements OnInit{
type = 'play'; type = 'play';
constructor() { constructor() {
const tp = this.getQueryString('type'); let tp = this.getQueryString("type");
if (tp) { if (tp){
this.type = tp; this.type = tp;
} }
} }
......
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import {MyErrorHandler} from './MyError';
import { AppComponent } from './app.component'; import { BrowserModule } from '@angular/platform-browser';
import { NgZorroAntdModule, NZ_I18N, zh_CN } from 'ng-zorro-antd'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgZorroAntdModule, NZ_I18N, zh_CN } from 'ng-zorro-antd';
import { NzButtonModule } from 'ng-zorro-antd/button';
import {Angular2FontawesomeModule} from 'angular2-fontawesome/angular2-fontawesome';
import { AppComponent } from './app.component';
import { FormComponent } from './form/form.component';
import { PlayComponent } from "./play/play.component";
// import { ColorPickerModule } from 'ngx-color-picker';
import { LessonTitleConfigComponent } from './common/lesson-title-config/lesson-title-config.component';
import { AudioRecorderComponent } from './common/audio-recorder/audio-recorder.component';
import { PlayerContentWrapperComponent } from './common/player-content-wrapper/player-content-wrapper.component';
/** 配置 angular i18n **/
import { registerLocaleData } from '@angular/common'; import { registerLocaleData } from '@angular/common';
import zh from '@angular/common/locales/zh'; import zh from '@angular/common/locales/zh';
import {FormComponent} from './form/form.component'; import {UploadImageWithPreviewComponent} from "./common/upload-image-with-preview/upload-image-with-preview.component";
import {PlayComponent} from './play/play.component'; import {BackgroundImagePipe} from "./pipes/background-image.pipe";
import {LessonTitleConfigComponent} from './common/lesson-title-config/lesson-title-config.component'; import {UploadVideoComponent} from "./common/upload-video/upload-video.component";
import {BackgroundImagePipe} from './pipes/background-image.pipe'; import {ResourcePipe} from "./pipes/resource.pipe";
import {UploadImageWithPreviewComponent} from './common/upload-image-with-preview/upload-image-with-preview.component'; import {TimePipe} from "./pipes/time.pipe";
import {PlayerContentWrapperComponent} from './common/player-content-wrapper/player-content-wrapper.component'; import {CustomHotZoneComponent} from "./common/custom-hot-zone/custom-hot-zone.component";
import {CustomHotZoneComponent} from './common/custom-hot-zone/custom-hot-zone.component';
import {UploadVideoComponent} from './common/upload-video/upload-video.component';
import {TimePipe} from './pipes/time.pipe';
import {ResourcePipe} from './pipes/resource.pipe';
import {AudioRecorderComponent} from './common/audio-recorder/audio-recorder.component';
import { FontAwesomeModule, FaIconLibrary } from '@fortawesome/angular-fontawesome';
import { fas } from '@fortawesome/free-solid-svg-icons';
import { far } from '@fortawesome/free-regular-svg-icons';
registerLocaleData(zh); registerLocaleData(zh);
@NgModule({ @NgModule({
...@@ -40,26 +41,22 @@ registerLocaleData(zh); ...@@ -40,26 +41,22 @@ registerLocaleData(zh);
TimePipe, TimePipe,
UploadVideoComponent, UploadVideoComponent,
CustomHotZoneComponent, CustomHotZoneComponent,
PlayerContentWrapperComponent PlayerContentWrapperComponent
], ],
imports: [ imports: [
BrowserModule,
NgZorroAntdModule,
FormsModule, FormsModule,
HttpClientModule, HttpClientModule,
BrowserAnimationsModule, BrowserAnimationsModule,
FontAwesomeModule BrowserModule,
Angular2FontawesomeModule,
NgZorroAntdModule,
//ColorPickerModule
], ],
providers: [ /** 配置 ng-zorro-antd 国际化(文案 及 日期) **/
{provide: ErrorHandler, useClass: MyErrorHandler}, providers : [
{ provide: NZ_I18N, useValue: zh_CN } { provide: NZ_I18N, useValue: zh_CN }
], ],
bootstrap: [AppComponent] bootstrap: [AppComponent]
}) })
export class AppModule { export class AppModule { }
constructor(library: FaIconLibrary) {
library.addIconPacks(fas, far);
}
}
<div class="d-flex"> <div class="d-flex">
<div class="p-btn-record d-flex"> <div class="p-btn-record d-flex">
<div class="btn-clear" style="cursor: pointer" (click)="onBtnClearAudio()" *ngIf="withRmBtn && (audioUrl || audioBlob)"> <div
<fa-icon icon="times"></fa-icon> class="btn-clear"
(click)="onBtnClearAudio()"
*ngIf="withRmBtn && (audioUrl || audioBlob)"
>
<fa name="close"></fa>
</div> </div>
<div class="btn-record" *ngIf="type===Type.RECORD && !isUploading" <div
[class.p-recording]="isRecording" class="btn-record"
(click)="onBtnRecord()"> *ngIf="type === Type.RECORD && !isUploading"
<fa-icon icon="microphone"></fa-icon> [class.p-recording]="isRecording"
(click)="onBtnRecord()"
>
<i nz-icon nzType="audio" nzTheme="outline"></i>
Record Audio Record Audio
</div> </div>
<nz-upload <nz-upload
[nzAccept] = "'.mp3'" [nzAccept]="'.mp3'"
[nzShowUploadList]="false" [nzShowUploadList]="false"
[nzAction]="uploadUrl" [nzAction]="uploadUrl"
[nzData]="uploadData" [nzData]="uploadData"
(nzChange)="handleChange($event)"> (nzChange)="handleChange($event)"
>
<div class="btn-upload" [ngClass]="{'has-clear': withRmBtn && (audioUrl || audioBlob)}" *ngIf="type===Type.UPLOAD && !isUploading"> <div
<fa-icon icon="upload"></fa-icon> class="btn-upload ng-star-inserted"
[ngClass]="{ 'has-clear': withRmBtn && (audioUrl || audioBlob) }"
*ngIf="type === Type.UPLOAD && !isUploading"
>
<i nz-icon nzType="cloud-upload" nzTheme="outline"></i>
Upload Audio Upload Audio
</div> </div>
</nz-upload> </nz-upload>
<div class="p-upload-progress-bg" *ngIf="isUploading"> <div class="p-upload-progress-bg" *ngIf="isUploading">
<div class="i-bg" [style.width]="progress+'%'"></div> <div class="i-bg" [style.width]="progress + '%'"></div>
<div class="i-text"> <div class="i-text">
<fa-icon icon="cloud-upload-alt"></fa-icon> <i nz-icon nzType="loading" nzTheme="outline"></i>
Uploading... Uploading...
</div> </div>
</div> </div>
<div
*ngIf="audioUrl && needRemove; then truthyTemplate; else falsyTemplate"
></div>
<div *ngIf="audioUrl && needRemove; then truthyTemplate else falsyTemplate"></div> <ng-template #truthyTemplate>
<ng-template #truthyTemplate >
<div class="btn-delete" (click)="onBtnDeleteAudio()"> <div class="btn-delete" (click)="onBtnDeleteAudio()">
<fa-icon icon="close"></fa-icon> <i nz-icon nzType="close" nzTheme="outline"></i>
</div> </div>
</ng-template> </ng-template>
<ng-template #falsyTemplate> <ng-template #falsyTemplate>
<div class="btn-switch" (click)="onBtnSwitchType()"> <div class="btn-switch" (click)="onBtnSwitchType()">
<fa-icon icon="cog"></fa-icon> <i nz-icon nzType="setting" nzTheme="outline"></i>
</div> </div>
</ng-template> </ng-template>
</div> </div>
<div class="p-progress ml-2" (click)="onBtnPlay()" *ngIf="audioUrl || audioBlob"> <div
<nz-progress [nzPercent]="percent" [nzWidth]="30" [nzFormat]="progressText" class="p-progress ml-2"
nzType="circle"></nz-progress> (click)="onBtnPlay()"
<div class="p-btn-play" [style.left]="isPlaying?'8px':''"> *ngIf="audioUrl || audioBlob"
<fa-icon [icon]="playIcon"></fa-icon> >
<nz-progress
[nzPercent]="percent"
[nzWidth]="30"
[nzFormat]="progressText"
nzType="circle"
></nz-progress>
<div class="p-btn-play" [style.left]="isPlaying ? '8px' : ''">
<i nz-icon nzType="caret-right" nzTheme="outline"></i>
</div> </div>
</div> </div>
</div> </div>
.d-flex{
display: flex;
}
.p-btn-record { .p-btn-record {
font-size: 0.9rem; font-size: 0.9rem;
color: #555; color: #555;
...@@ -91,6 +88,7 @@ ...@@ -91,6 +88,7 @@
.p-progress { .p-progress {
margin-top: 2px; margin-top: 2px;
margin-left: 5px;
position: relative; position: relative;
line-height: 26px; line-height: 26px;
.p-btn-play { .p-btn-play {
...@@ -105,3 +103,6 @@ ...@@ -105,3 +103,6 @@
line-height: 33px; line-height: 33px;
} }
.d-flex{
display: flex;
}
\ No newline at end of file
import {Component, EventEmitter, Input, OnDestroy, OnInit, Output, NgZone, OnChanges} from '@angular/core'; import {Component, EventEmitter, Input, OnDestroy, OnInit, Output, NgZone, OnChanges} from '@angular/core';
import {NzMessageService, NzNotificationService, UploadFile} from 'ng-zorro-antd'; import {NzMessageService, NzNotificationService, UploadFile} from 'ng-zorro-antd';
import {HttpClient, HttpEvent, HttpEventType, HttpRequest} from '@angular/common/http'; import {HttpClient, HttpEvent, HttpEventType, HttpRequest} from '@angular/common/http';
import {environment} from '../../../environments/environment'; import {environment} from '../../../environments/environment';
declare var Recorder; declare var Recorder;
...@@ -9,7 +9,7 @@ declare var Recorder; ...@@ -9,7 +9,7 @@ declare var Recorder;
selector: 'app-audio-recorder', selector: 'app-audio-recorder',
templateUrl: './audio-recorder.component.html', templateUrl: './audio-recorder.component.html',
styleUrls: ['./audio-recorder.component.scss'] styleUrls: ['./audio-recorder.component.scss']
}) })
export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy { export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
_audioUrl: string; _audioUrl: string;
audio = new Audio(); audio = new Audio();
...@@ -19,11 +19,10 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy { ...@@ -19,11 +19,10 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
isUploading = false; isUploading = false;
type = Type.UPLOAD; // record | upload type = Type.UPLOAD; // record | upload
Type = Type; Type = Type;
@Input()
withRmBtn = false; withRmBtn = false;
uploadUrl; uploadUrl = (<any>window).courseware.uploadUrl();
uploadData; uploadData = (<any>window).courseware.uploadData();
@Input() @Input()
needRemove = false; needRemove = false;
...@@ -33,7 +32,7 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy { ...@@ -33,7 +32,7 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
@Input() @Input()
set audioUrl(url) { set audioUrl(url) {
this._audioUrl = url; this._audioUrl = url
if (url) { if (url) {
this.audio.src = this._audioUrl; this.audio.src = this._audioUrl;
this.audio.load(); this.audio.load();
...@@ -53,15 +52,9 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy { ...@@ -53,15 +52,9 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
recorder: any; recorder: any;
audioBlob: any; audioBlob: any;
constructor( private nzMessageService: NzMessageService ) {
constructor( private nzMessageService: NzMessageService ) {
this.uploadUrl = (<any> window).courseware.uploadUrl();
this.uploadData = (<any> window).courseware.uploadData();
window['air'].getUploadCallback = (url, data) => {
this.uploadUrl = url;
this.uploadData = data;
};
} }
init() { init() {
...@@ -144,14 +137,13 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy { ...@@ -144,14 +137,13 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
} }
// 开始录音 // 开始录音
onBtnRecord = () => { onBtnRecord = () => {
} }
// 切换模式 // 切换模式
onBtnSwitchType() { onBtnSwitchType() {
} }
onBtnClearAudio() { onBtnClearAudio() {
this.audioUrl = null;
this.audioRemoved.emit(); this.audioRemoved.emit();
} }
...@@ -160,7 +152,7 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy { ...@@ -160,7 +152,7 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
this.audioRemoved.emit(); this.audioRemoved.emit();
} }
handleChange(info: { type: string, file: UploadFile, event: any }): void { handleChange(info: { type: string, file: UploadFile, event: any }): void {
switch (info.type) { switch (info.type) {
case 'start': case 'start':
this.isUploading = true; this.isUploading = true;
...@@ -193,19 +185,22 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy { ...@@ -193,19 +185,22 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
} }
return true; return true;
} }
beforeUpload = (file: File) => { beforeUpload = (file: File) => {
this.audioUrl = null; this.audioUrl = null;
if (!this.checkSelectFile(file)) { if (!this.checkSelectFile(file)) {
return false; return false;
} }
this.isUploading = true; this.isUploading = true;
this.progress = 0; this.progress = 0;
} }
uploadSuccess = (url) => { uploadSuccess = (url) => {
this.nzMessageService.info('Upload Success'); this.nzMessageService.info('Upload Success');
this.isUploading = false; this.isUploading = false;
this.audioUrl = url; if(typeof url == "string"){
this.audioUrl = url
}else{
this.audioUrl = url.url
}
} }
uploadFailure = (err, file) => { uploadFailure = (err, file) => {
this.isUploading = false; this.isUploading = false;
......
import TWEEN from '@tweenjs/tween.js'; import TWEEN from '@tweenjs/tween.js';
interface AirWindow extends Window {
air: any;
curCtx: any;
}
declare let window: AirWindow;
class Sprite { class Sprite {
x = 0; x = 0;
...@@ -17,12 +12,8 @@ class Sprite { ...@@ -17,12 +12,8 @@ class Sprite {
angle = 0; angle = 0;
ctx; ctx;
constructor(ctx = null) { constructor(ctx) {
if (!ctx) { this.ctx = ctx;
this.ctx = window.curCtx;
} else {
this.ctx = ctx;
}
} }
update($event) { update($event) {
this.draw(); this.draw();
...@@ -39,195 +30,80 @@ class Sprite { ...@@ -39,195 +30,80 @@ class Sprite {
export class MySprite extends Sprite { export class MySprite extends Sprite {
_width = 0; width = 0;
_height = 0; height = 0;
_anchorX = 0; _anchorX = 0;
_anchorY = 0; _anchorY = 0;
_offX = 0; _offX = 0;
_offY = 0; _offY = 0;
scaleX = 1; scaleX = 1;
scaleY = 1; scaleY = 1;
_alpha = 1; alpha = 1;
rotation = 0; rotation = 0;
visible = true; visible = true;
skewX = 0; offSetCenter = false;
skewY = 0;
_shadowFlag = false;
_shadowColor;
_shadowOffsetX = 0;
_shadowOffsetY = 0;
_shadowBlur = 5;
_radius = 0;
children = [this]; children = [this];
childDepandVisible = true;
childDepandAlpha = false;
img; img;
_z = 0; _z = 0;
_showRect;
_bitmapFlag = false;
_offCanvas;
_offCtx;
init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) {
init(imgObj = null, anchorX:number = 0.5, anchorY:number = 0.5) {
if (imgObj) { if (imgObj) {
this.img = imgObj; this.img = imgObj;
this.width = this.img.width; this.width = this.img.width;
this.height = this.img.height; this.height = this.img.height;
} }
this.anchorX = anchorX; this.anchorX = anchorX;
this.anchorY = anchorY; this.anchorY = anchorY;
} }
setShowRect(rect) {
this._showRect = rect;
}
setShadow(offX, offY, blur, color = 'rgba(0, 0, 0, 0.3)') {
this._shadowFlag = true;
this._shadowColor = color;
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
this._shadowBlur = blur;
}
setRadius(r) {
this._radius = r;
}
update($event = null) { update($event = null) {
if (!this.visible && this.childDepandVisible) { if (this.visible) {
return; this.draw();
} }
this.draw();
} }
draw() { draw() {
this.ctx.save(); this.ctx.save();
this.drawInit(); this.drawInit();
this.updateChildren(); this.updateChildren();
this.ctx.restore(); this.ctx.restore();
} }
drawInit() { drawInit() {
this.ctx.translate(this.x, this.y); this.ctx.translate(this.x, this.y);
this.ctx.rotate(this.rotation * Math.PI / 180); this.ctx.rotate(this.rotation * Math.PI / 180);
this.ctx.scale(this.scaleX, this.scaleY); this.ctx.scale(this.scaleX, this.scaleY);
this.ctx.globalAlpha = this.alpha; this.ctx.globalAlpha = this.alpha;
if(this.offSetCenter){
this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0); this.ctx.translate( -( this.width * this.anchorX ), -( this.height * this.anchorY ) );
}
//
// if (this._radius) {
//
// const r = this._radius;
// const w = this.width;
// const h = this.height;
//
// this.ctx.lineTo(-w / 2, h / 2); // 创建水平线
// this.ctx.arcTo(-w / 2, -h / 2, -w / 2 + r, -h / 2, r);
// this.ctx.arcTo(w / 2, -h / 2, w / 2, -h / 2 + r, r);
// this.ctx.arcTo(w / 2, h / 2, w / 2 - r, h / 2, r);
// this.ctx.arcTo(-w / 2, h / 2, -w / 2, h / 2 - r, r);
//
// this.ctx.clip();
// }
} }
drawSelf() { drawSelf() {
if (this._shadowFlag) {
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
this.ctx.shadowBlur = this._shadowBlur;
this.ctx.shadowColor = this._shadowColor;
} else {
this.ctx.shadowOffsetX = 0;
this.ctx.shadowOffsetY = 0;
this.ctx.shadowBlur = null;
this.ctx.shadowColor = null;
}
if (this.img) { if (this.img) {
this.ctx.drawImage(this.img, this._offX, this._offY);
if (this._showRect) {
const rect = this._showRect;
this.ctx.drawImage(this.img, rect.x, rect.y, rect.width, rect.height, this._offX, this._offY + rect.y, this.width, rect.height);
} else {
this.ctx.drawImage(this.img, this._offX, this._offY);
}
} }
} }
updateChildren() { updateChildren() {
if (this.children.length <= 0) { return; } if (this.children.length <= 0) { return; }
for (let i = 0; i < this.children.length; i++) {
for (const child of this.children) { if (this.children[i] === this) {
if (child === this) { this.drawSelf();
if (this.visible) {
this.drawSelf();
}
} else { } else {
child.update(); this.children[i].update();
} }
} }
} }
load(url, anchorX = 0.5, anchorY = 0.5) { load(url, anchorX = 0.5, anchorY = 0.5) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const img = new Image(); const img = new Image();
img.onload = () => resolve(img); img.onload = () => resolve(img);
img.onerror = reject; img.onerror = reject;
img.src = url; img.src = url;
}).then(img => { }).then(img => {
this.init(img, anchorX, anchorY); this.init(img, anchorX, anchorY);
return img; return img;
}); });
...@@ -239,17 +115,11 @@ export class MySprite extends Sprite { ...@@ -239,17 +115,11 @@ export class MySprite extends Sprite {
child._z = z; child._z = z;
child.parent = this; child.parent = this;
} }
this.children.sort((a, b) => { this.children.sort((a, b) => {
return a._z - b._z; return a._z - b._z;
}); });
if (this.childDepandAlpha) {
child.alpha = this.alpha;
}
} }
removeChild(child) { removeChild(child) {
const index = this.children.indexOf(child); const index = this.children.indexOf(child);
if (index !== -1) { if (index !== -1) {
...@@ -257,55 +127,6 @@ export class MySprite extends Sprite { ...@@ -257,55 +127,6 @@ export class MySprite extends Sprite {
} }
} }
removeChildren() {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i]) {
if (this.children[i] !== this) {
this.children.splice(i, 1);
i --;
}
}
}
}
_changeChildAlpha(alpha) {
for (const child of this.children) {
if (child !== this) {
child.alpha = alpha;
}
}
}
set btimapFlag(v) {
this._bitmapFlag = v;
}
get btimapFlag() {
return this._bitmapFlag;
}
set alpha(v) {
this._alpha = v;
if (this.childDepandAlpha) {
this._changeChildAlpha(v);
}
}
get alpha() {
return this._alpha;
}
set width(v) {
this._width = v;
this.refreshAnchorOff();
}
get width() {
return this._width;
}
set height(v) {
this._height = v;
this.refreshAnchorOff();
}
get height() {
return this._height;
}
set anchorX(value) { set anchorX(value) {
this._anchorX = value; this._anchorX = value;
this.refreshAnchorOff(); this.refreshAnchorOff();
...@@ -321,8 +142,8 @@ export class MySprite extends Sprite { ...@@ -321,8 +142,8 @@ export class MySprite extends Sprite {
return this._anchorY; return this._anchorY;
} }
refreshAnchorOff() { refreshAnchorOff() {
this._offX = -this._width * this.anchorX; this._offX = -this.width * this.anchorX;
this._offY = -this._height * this.anchorY; this._offY = -this.height * this.anchorY;
} }
setScaleXY(value) { setScaleXY(value) {
...@@ -330,1684 +151,184 @@ export class MySprite extends Sprite { ...@@ -330,1684 +151,184 @@ export class MySprite extends Sprite {
} }
getBoundingBox() { getBoundingBox() {
const x = this.x + this._offX * this.scaleX;
const getParentData = (item) => { const y = this.y + this._offY * this.scaleY;
const width = this.width * this.scaleX;
let px = item.x; const height = this.height * this.scaleY;
let py = item.y;
let sx = item.scaleX;
let sy = item.scaleY;
const parent = item.parent;
if (parent) {
const obj = getParentData(parent);
const _x = obj.px;
const _y = obj.py;
const _sx = obj.sx;
const _sy = obj.sy;
px = _x + item.x * _sx;
py = _y + item.y * _sy;
sx *= _sx;
sy *= _sy;
}
return {px, py, sx, sy};
};
const data = getParentData(this);
const x = data.px + this._offX * Math.abs(data.sx);
const y = data.py + this._offY * Math.abs(data.sy);
const width = this.width * Math.abs(data.sx);
const height = this.height * Math.abs(data.sy);
return {x, y, width, height}; return {x, y, width, height};
} }
} }
export class RoundSprite extends MySprite { export class Item extends MySprite {
baseX;
_newCtx; move(targetY, callBack) {
const self = this;
init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) { const tween = new TWEEN.Tween(this)
.to({ y: targetY }, 2500)
if (imgObj) { .easing(TWEEN.Easing.Quintic.Out)
.onComplete(function() {
this.img = imgObj; self.hide(callBack);
// if (callBack) {
this.width = this.img.width; // callBack();
this.height = this.img.height; // }
})
.start();
}
this.anchorX = anchorX;
this.anchorY = anchorY;
const canvas = window['curCanvas'];
const w = canvas.nativeElement.width;
const h = canvas.nativeElement.height;
this._offCanvas = document.createElement('canvas');
this._offCanvas.width = w;
this._offCanvas.height = h;
this._offCtx = this._offCanvas.getContext('2d');
// this._newCtx = this.ctx;
// this.ctx = this._offCtx;
}
drawSelf() {
//
// if (this._shadowFlag) {
//
// this.ctx.shadowOffsetX = this._shadowOffsetX;
// this.ctx.shadowOffsetY = this._shadowOffsetY;
// this.ctx.shadowBlur = this._shadowBlur;
// this.ctx.shadowColor = this._shadowColor;
// } else {
// this.ctx.shadowOffsetX = 0;
// this.ctx.shadowOffsetY = 0;
// this.ctx.shadowBlur = null;
// this.ctx.shadowColor = null;
// }
if (this._radius) {
const r = this._radius;
const w = this.width;
const h = this.height;
const x = -this._offX;
const y = -this._offY;
this._offCtx.lineTo(x - w / 2, y + h / 2); // 创建水平线
this._offCtx.arcTo(x - w / 2, y - h / 2, x - w / 2 + r, y - h / 2, r);
this._offCtx.arcTo(x + w / 2, y - h / 2, x + w / 2, y - h / 2 + r, r);
this._offCtx.arcTo(x + w / 2, y + h / 2, x + w / 2 - r, y + h / 2, r);
this._offCtx.arcTo(x - w / 2, y + h / 2, x - w / 2, y + h / 2 - r, r);
this._offCtx.clip();
}
if (this.img) {
this._offCtx.drawImage(this.img, 0, 0);
this.ctx.drawImage(this._offCanvas,this._offX, this._offX);
}
} }
} show(callBack = null) {
const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(function() {
if (callBack) {
export class ColorSpr extends MySprite { callBack();
}
r = 0; })
g = 0; .start(); // Start the tween immediately.
b = 0;
createGSCanvas() {
if (!this.img) {
return;
}
const rect = this.getBoundingBox();
if (rect.width <= 1 || rect.height <= 1) {
return;
}
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for ( let i = 0; i < c.height; i++) {
for ( let j = 0; j < c.width; j++) {
const x = (i * 4) * c.width + ( j * 4 );
const r = c.data[x];
const g = c.data[x + 1];
const b = c.data[x + 2];
c.data[x] = this.r;
c.data[x + 1] = this.g;
c.data[x + 2] = this.b;
// c.data[x] = c.data[x + 1] = c.data[x + 2] = (r + g + b) / 3 ;
// // c.data[x + 3] = 255;
}
}
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
} }
hide(callBack = null) {
drawSelf() { const tween = new TWEEN.Tween(this)
super.drawSelf(); .to({ alpha: 0 }, 800)
this.createGSCanvas(); // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(function() {
if (callBack) {
callBack();
}
})
.start(); // Start the tween immediately.
} }
}
export class GrayscaleSpr extends MySprite { shake(id) {
if (!this.baseX) {
grayScale = 120; this.baseX = this.x;
createGSCanvas() {
if (!this.img) {
return;
} }
const baseX = this.baseX;
const baseTime = 50;
const rect = this.getBoundingBox(); const sequence = [
{target: {x: baseX + 40 * id}, time: baseTime - 25},
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height); {target: {x: baseX - 20 * id}, time: baseTime},
for ( let i = 0; i < c.height; i++) { {target: {x: baseX + 10 * id}, time: baseTime},
for ( let j = 0; j < c.width; j++) { {target: {x: baseX - 5 * id}, time: baseTime},
{target: {x: baseX + 2 * id}, time: baseTime},
const x = (i * 4) * c.width + ( j * 4 ); {target: {x: baseX - 1 * id}, time: baseTime},
const r = c.data[x]; {target: {x: baseX}, time: baseTime},
const g = c.data[x + 1]; ];
const b = c.data[x + 2]; const self = this;
// const a = c.data[x + 3]; function runSequence() {
if (self['shakeTween']) {
c.data[x] = c.data[x + 1] = c.data[x + 2] = this.grayScale; // (r + g + b) / 3; self['shakeTween'].stop();
// c.data[x + 3] = 255; }
const tween = new TWEEN.Tween(self);
if (sequence.length > 0) {
const action = sequence.shift();
tween.to(action['target'], action['time']);
tween.onComplete( () => {
runSequence();
});
tween.start();
self['shakeTween'] = tween;
} }
} }
runSequence();
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
} }
drop(targetY, callBack = null) {
drawSelf() { const self = this;
super.drawSelf(); const time = Math.abs(targetY - this.y) * 2.4;
this.createGSCanvas(); this.alpha = 1;
const tween = new TWEEN.Tween(this)
.to({ y: targetY }, time)
.easing(TWEEN.Easing.Cubic.In)
.onComplete(function() {
// self.hideItem(callBack);
if (callBack) {
callBack();
}
})
.start();
} }
} }
export class EndSpr extends MySprite {
show(s) {
this.scaleX = this.scaleY = 0;
this.alpha = 0;
const tween = new TWEEN.Tween(this)
.to({ alpha: 1, scaleX: s, scaleY: s }, 800)
.easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
.onComplete(function() {
})
.start(); // Start the tween immediately.
export class BitMapLabel extends MySprite {
labelArr;
baseUrl;
setText(data, text) {
this.labelArr = [];
const labelArr = [];
const tmpArr = text.split('');
let totalW = 0;
let h = 0;
for (const tmp of tmpArr) {
const label = new MySprite(this.ctx);
label.init(data[tmp], 0);
this.addChild(label);
labelArr.push(label);
totalW += label.width;
h = label.height;
}
this.width = totalW;
this.height = h;
let offX = -totalW / 2;
for (const label of labelArr) {
label.x = offX;
offX += label.width;
}
this.labelArr = labelArr;
} }
} }
export class ShapeRect extends MySprite {
fillColor = '#FF0000';
setSize(w, h) {
export class Label extends MySprite { this.width = w;
private _text: string; this.height = h;
// fontSize:String = '40px';
fontName = 'Verdana';
textAlign = 'left';
fontSize = 40;
fontColor = '#000000';
fontWeight = 900;
_maxWidth;
outline = 0;
outlineColor = '#ffffff';
// _shadowFlag = false;
// _shadowColor;
// _shadowOffsetX;
// _shadowOffsetY;
// _shadowBlur;
_outlineFlag = false;
_outLineWidth;
_outLineColor;
constructor(ctx = null) {
super(ctx);
this.init();
}
get text(): string {
return this._text;
}
set text(value: string) {
this._text = value;
this.refreshSize();
}
refreshSize() {
this.ctx.save();
this.ctx.font = `${this.fontSize * this.scaleX}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
this._width = this.ctx.measureText(this.text).width;
this._height = this.fontSize;
this.refreshAnchorOff();
this.ctx.restore();
}
setMaxSize(w) {
this._maxWidth = w;
this.refreshSize();
if (this.width >= w) {
this.scaleX *= w / this.width;
this.scaleY *= w / this.width;
}
}
show(callBack = null) {
this.visible = true;
if (this.alpha >= 1) {
return;
}
const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
})
.start(); // Start the tween immediately.
}
setOutline(width = 5, color = '#ffffff') {
this._outlineFlag = true;
this._outLineWidth = width;
this._outLineColor = color;
}
drawText() {
if (!this.text) { return; }
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor;
this.ctx.strokeText(this.text, 0, 0);
}
this.ctx.fillStyle = this.fontColor;
if (this.outline > 0) {
this.ctx.lineWidth = this.outline;
this.ctx.strokeStyle = this.outlineColor;
this.ctx.strokeText(this.text, 0, 0);
}
this.ctx.fillText(this.text, 0, 0);
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class RichTextOld extends Label {
textArr = [];
fontSize = 40;
setText(text: string, words) {
let newText = text;
for (const word of words) {
const re = new RegExp(word, 'g');
newText = newText.replace( re, `#${word}#`);
// newText = newText.replace(word, `#${word}#`);
}
this.textArr = newText.split('#');
this.text = newText;
// this.setSize();
}
refreshSize() {
this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
let curX = 0;
for (const text of this.textArr) {
const w = this.ctx.measureText(text).width;
curX += w;
}
this.width = curX;
this.height = this.fontSize;
this.refreshAnchorOff();
this.ctx.restore();
}
show(callBack = null) {
// console.log(' in show ');
this.visible = true;
// this.alpha = 0;
const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
})
.start(); // Start the tween immediately.
}
drawText() {
// console.log('in drawText', this.text);
if (!this.text) { return; }
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = 900;
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = '#ffffff';
// this.ctx.strokeText(this.text, 0, 0);
this.ctx.fillStyle = '#000000';
// this.ctx.fillText(this.text, 0, 0);
let curX = 0;
for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width;
if ((i + 1) % 2 === 0) {
this.ctx.fillStyle = '#c8171e';
} else {
this.ctx.fillStyle = '#000000';
}
this.ctx.fillText(this.textArr[i], curX, 0);
curX += w;
}
}
}
export class RichText extends Label {
disH = 30;
constructor(ctx?: any) {
super(ctx);
// this.dataArr = dataArr;
}
drawText() {
if (!this.text) {
return;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
this.ctx.fillStyle = this.fontColor;
const selfW = this.width * this.scaleX;
const chr = this.text.split(' ');
let temp = '';
const row = [];
const w = selfW - 80;
const disH = (this.fontSize + this.disH) * this.scaleY;
for (const c of chr) {
if (this.ctx.measureText(temp).width < w && this.ctx.measureText(temp + (c)).width <= w) {
temp += ' ' + c;
} else {
row.push(temp);
temp = ' ' + c;
}
}
row.push(temp);
const x = 0;
const y = -row.length * disH / 2;
// for (let b = 0 ; b < row.length; b++) {
// this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
// }
if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor;
for (let b = 0 ; b < row.length; b++) {
this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
}
// this.ctx.strokeText(this.text, 0, 0);
}
// this.ctx.fillStyle = '#ff7600';
for (let b = 0 ; b < row.length; b++) {
this.ctx.fillText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
}
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class LineRect extends MySprite {
lineColor = '#ffffff';
lineWidth = 10;
setSize(w, h) {
this.width = w;
this.height = h;
}
drawLine() {
this.ctx.beginPath();
this.ctx.moveTo(this._offX, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY + this.height);
this.ctx.lineTo(this._offX, this._offY + this.height);
this.ctx.closePath();
this.ctx.lineWidth = this.lineWidth;
// this.ctx.fillStyle = "rgb(2,33,42)"; //指定填充颜色
// this.ctx.fill(); //对多边形进行填充
this.ctx.strokeStyle = this.lineColor; // "#ffffff";
this.ctx.stroke();
}
drawSelf() {
super.drawSelf();
this.drawLine();
}
}
export class ShapeRect extends MySprite {
fillColor = '#FF0000';
setSize(w, h) {
this.width = w;
this.height = h;
// console.log('w:', w);
// console.log('h:', h);
} }
drawShape() { drawShape() {
this.ctx.fillStyle = this.fillColor; this.ctx.fillStyle = this.fillColor;
this.ctx.fillRect(this._offX, this._offY, this.width, this.height); this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
}
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class Line extends MySprite {
lineWidth = 5;
lineColor = '#000000';
_pointArr = [];
roundFlag = true;
_pointS = 1;
imgObj;
bitMap;
_offCtx;
_offCanvas;
lastPointIndex = 0;
init() {
const canvas = window['curCanvas'];
const w = canvas.nativeElement.width;
const h = canvas.nativeElement.height;
console.log('w: ', w);
console.log('h: ', h);
this._offCanvas = document.createElement('canvas');
this._offCanvas.width = w;
this._offCanvas.height = h;
// this._offCanvas = _offCanvas;
// this._offCtx = this._offCanvas.getContext('2d');
// this._offCanvas = new OffscreenCanvas(w, h);
this._offCtx = this._offCanvas.getContext('2d');
}
addPoint(x, y) {
this._pointArr.push([x, y]);
if (this._pointArr.length < 2) {
return;
}
//
// const lastP = this._pointArr[this._pointArr.length - 1];
//
//
// const context = this._offCtx;
// context.moveTo (lastP[0], lastP[1]); // 设置起点状态
// context.lineTo (x, y); // 设置末端状态
//
// context.lineWidth = this.lineWidth; //设置线宽状态
// context.strokeStyle = this.lineColor;
// context.stroke();
//
//
// this.bitMap = this._offCanvas.transferToImageBitmap();
// const tmpLine = new MySprite(this._offCtx);
// tmpLine.init(this.imgObj);
// tmpLine.anchorY = 1;
// tmpLine.anchorX = 0.5;
// tmpLine.x = lastP[0];
// tmpLine.y = lastP[1];
//
// const disH = getPosDistance(lastP[0], lastP[1], x, y);
// tmpLine.scaleX = this.lineWidth / tmpLine.width;
// tmpLine.scaleY = disH / tmpLine.height * 1.1;
//
// const angle = getAngleByPos(lastP[0], lastP[1], x, y);
// tmpLine.rotation = angle;
//
// this.addChild(tmpLine);
}
setPointArr(arr, imgObj) {
this.removeChildren();
if (arr.length < 2) {
return;
}
let p1 = arr[0];
let p2;
for (let i = 1; i < arr.length; i++) {
p2 = arr[i];
const tmpLine = new MySprite();
tmpLine.init(imgObj);
tmpLine.anchorY = 1;
tmpLine.anchorX = 0.5;
tmpLine.x = p1[0];
tmpLine.y = p1[1];
const disH = getPosDistance(p1[0], p1[1], p2[0], p2[1]);
tmpLine.scaleX = this.lineWidth / tmpLine.width;
tmpLine.scaleY = disH / tmpLine.height * 1.1;
const angle = getAngleByPos(p1[0], p1[1], p2[0], p2[1]);
tmpLine.rotation = angle;
this.addChild(tmpLine);
p1 = p2;
}
}
drawLine() {
if (this._pointArr.length < 2) {
return;
}
const curMaxPointIndex = this._pointArr.length - 1;
if (curMaxPointIndex > this.lastPointIndex) {
const arr = this._pointArr;
const context = this._offCtx;
context.moveTo (arr[this.lastPointIndex][0] * this._pointS, arr[this.lastPointIndex][1] * this._pointS); // 设置起点状态
for (let i = this.lastPointIndex + 1; i < arr.length; i++) {
context.lineTo (arr[i][0] * this._pointS, arr[i][1] * this._pointS); // 设置末端状态
}
if (this.roundFlag) {
context.lineCap = "round";
}
context.lineWidth = this.lineWidth; //设置线宽状态
context.strokeStyle = this.lineColor;
context.stroke();
this.lastPointIndex = curMaxPointIndex;
// this.bitMap = this._offCanvas.transferToImageBitmap();
}
// this.ctx.drawImage(this.bitMap, this._offX, this._offY);
this.ctx.drawImage(this._offCanvas, this._offX, this._offY);
}
drawSelf() {
super.drawSelf();
this.drawLine();
// if (this.img) {
// this.ctx.drawImage(this._offCanvas, 0, 0, this.width, this.height);
// }
// if (this.bitMap) {
// this.bitMap = this._offCanvas.transferToImageBitmap();
// this.ctx.drawImage(this.bitMap, 0, 0, this.width, this.height);
// }
}
}
export class ShapeCircle extends MySprite {
fillColor = '#FF0000';
radius = 0;
setRadius(r) {
this.anchorX = this.anchorY = 0.5;
this.radius = r;
this.width = r * 2;
this.height = r * 2;
}
drawShape() {
this.ctx.beginPath();
this.ctx.fillStyle = this.fillColor;
this.ctx.arc(0, 0, this.radius, 0, angleToRadian(360));
this.ctx.fill();
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class ShapeRectNew extends MySprite {
radius = 0;
fillColor = '#ffffff';
strokeColor = '#000000';
fill = true;
stroke = false;
lineWidth = 1;
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
drawShape() {
const ctx = this.ctx;
const width = this.width;
const height = this.height;
const radius = this.radius;
ctx.save();
ctx.beginPath(0);
// 从右下角顺时针绘制,弧度从0到1/2PI
ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
// 矩形下边线
ctx.lineTo(radius, height);
// 左下角圆弧,弧度从1/2PI到PI
ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
// 矩形左边线
ctx.lineTo(0, radius);
// 左上角圆弧,弧度从PI到3/2PI
ctx.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
// 上边线
ctx.lineTo(width - radius, 0);
// 右上角圆弧
ctx.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
// 右边线
ctx.lineTo(width, height - radius);
ctx.closePath();
if (this.fill) {
ctx.fillStyle = this.fillColor;
ctx.fill();
}
if (this.stroke) {
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.strokeColor;
ctx.stroke();
}
ctx.restore();
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class MyAnimation extends MySprite {
frameArr = [];
frameIndex = 0;
playFlag = false;
lastDateTime;
curDelay = 0;
loop = false;
playEndFunc;
delayPerUnit = 1;
restartFlag = false;
reverseFlag = false;
addFrameByImg(img) {
const spr = new MySprite(this.ctx);
spr.init(img);
this._refreshSize(img);
spr.visible = false;
this.addChild(spr);
this.frameArr.push(spr);
this.frameArr[this.frameIndex].visible = true;
}
addFrameByUrl(url) {
const spr = new MySprite(this.ctx);
spr.load(url).then(img => {
this._refreshSize(img);
});
spr.visible = false;
this.addChild(spr);
this.frameArr.push(spr);
this.frameArr[this.frameIndex].visible = true;
}
_refreshSize(img: any) {
if (this.width < img.width) {
this.width = img.width;
}
if (this.height < img.height) {
this.height = img.height;
}
}
play() {
this.playFlag = true;
this.lastDateTime = new Date().getTime();
}
stop() {
this.playFlag = false;
}
replay() {
this.restartFlag = true;
this.play();
}
reverse() {
this.reverseFlag = !this.reverseFlag;
this.frameArr.reverse();
this.frameIndex = 0;
}
showAllFrame() {
for (const frame of this.frameArr ) {
frame.alpha = 1;
}
}
hideAllFrame() {
for (const frame of this.frameArr) {
frame.alpha = 0;
}
}
playEnd() {
this.playFlag = false;
this.curDelay = 0;
this.frameArr[this.frameIndex].visible = true;
if (this.playEndFunc) {
this.playEndFunc();
this.playEndFunc = null;
}
}
updateFrame() {
if (this.frameArr[this.frameIndex]) {
this.frameArr[this.frameIndex].visible = false;
}
this.frameIndex ++;
if (this.frameIndex >= this.frameArr.length) {
if (this.loop) {
this.frameIndex = 0;
} else if (this.restartFlag) {
this.restartFlag = false;
this.frameIndex = 0;
} else {
this.frameIndex -- ;
this.playEnd();
return;
}
}
this.frameArr[this.frameIndex].visible = true;
}
_updateDelay(delay) {
this.curDelay += delay;
if (this.curDelay < this.delayPerUnit) {
return;
}
this.curDelay -= this.delayPerUnit;
this.updateFrame();
}
_updateLastDate() {
if (!this.playFlag) { return; }
let delay = 0;
if (this.lastDateTime) {
delay = (new Date().getTime() - this.lastDateTime) / 1000;
}
this.lastDateTime = new Date().getTime();
this._updateDelay(delay);
}
update($event: any = null) {
super.update($event);
this._updateLastDate();
}
}
// --------=========== util func =============-------------
export function tweenChange(item, obj, time = 0.8, callBack = null, easing = null, update = null) {
const tween = new TWEEN.Tween(item).to(obj, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
if (update) {
tween.onUpdate( (a, b) => {
update(a, b);
});
}
tween.start();
return tween;
}
export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function scaleItem(item, scale, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ scaleX: scale, scaleY: scale}, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.start();
return tween;
}
export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ x, y}, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.start();
return tween;
}
export function endShow(item, s = 1) {
item.scaleX = item.scaleY = 0;
item.alpha = 0;
const tween = new TWEEN.Tween(item)
.to({ alpha: 1, scaleX: s, scaleY: s }, 800)
.easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
})
.start();
}
export function hideItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha === 0) {
return;
}
const tween = new TWEEN.Tween(item)
.to({alpha: 0}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function showItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha === 1) {
if (callBack) {
callBack();
}
return;
}
item.visible = true;
const tween = new TWEEN.Tween(item)
.to({alpha: 1}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item)
.to({alpha}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function showStar(item, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item)
.to({alpha: 1, scale: 1}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function randomSortByArr(arr) {
if (!arr) {
return;
}
const newArr = [];
const tmpArr = arr.concat();
while (tmpArr.length > 0) {
const randomIndex = Math.floor( tmpArr.length * Math.random() );
newArr.push(tmpArr[randomIndex]);
tmpArr.splice(randomIndex, 1);
}
return newArr;
}
export function radianToAngle(radian) {
return radian * 180 / Math.PI;
// 角度 = 弧度 * 180 / Math.PI;
}
export function angleToRadian(angle) {
return angle * Math.PI / 180;
// 弧度= 角度 * Math.PI / 180;
}
export function getPosByAngle(angle, len) {
const radian = angle * Math.PI / 180;
const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len;
return {x, y};
}
export function getAngleByPos(px, py, mx, my) {
const x = Math.abs(px - mx);
const y = Math.abs(py - my);
const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
const cos = y / z;
const radina = Math.acos(cos); // 用反三角函数求弧度
let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度
if (mx > px && my > py) {// 鼠标在第四象限
angle = 180 - angle;
}
if (mx === px && my > py) {// 鼠标在y轴负方向上
angle = 180;
}
if (mx > px && my === py) {// 鼠标在x轴正方向上
angle = 90;
}
if (mx < px && my > py) {// 鼠标在第三象限
angle = 180 + angle;
}
if (mx < px && my === py) {// 鼠标在x轴负方向
angle = 270;
}
if (mx < px && my < py) {// 鼠标在第二象限
angle = 360 - angle;
}
// console.log('angle: ', angle);
return angle;
}
export function removeItemFromArr(arr, item) {
const index = arr.indexOf(item);
if (index !== -1) {
arr.splice(index, 1);
}
}
export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = 1, callBack = null, easing = null) {
const r = getPosDistance(item.x, item.y, x0, y0);
let a = getAngleByPos(item.x, item.y, x0, y0);
a += 90;
const obj = {r, a};
item._circleAngle = a;
const targetA = a + addR;
const tween = new TWEEN.Tween(item).to({_circleAngle: targetA}, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.onUpdate( (item, progress) => {
// console.log(item._circleAngle);
const r = obj.r;
const a = item._circleAngle;
const x = x0 + r * xPer * Math.cos(a * Math.PI / 180);
const y = y0 + r * yPer * Math.sin(a * Math.PI / 180);
item.x = x;
item.y = y;
// obj.a ++;
});
tween.start();
}
export function getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx;
const _y = ey - sy;
const len = Math.sqrt( Math.pow(_x, 2) + Math.pow(_y, 2) );
return len;
}
export function delayCall(callback, second) {
const tween = new TWEEN.Tween(this)
.delay(second * 1000)
.onComplete(() => {
if (callback) {
callback();
}
})
.start();
}
export function formatTime(fmt, date) {
// "yyyy-MM-dd HH:mm:ss";
const o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); }
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1)
? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return fmt;
}
export function getMinScale(item, maxLen) {
const sx = maxLen / item.width;
const sy = maxLen / item.height;
const minS = Math.min(sx, sy);
return minS;
}
export function jelly(item, time = 0.7) {
if (item.jellyTween) {
TWEEN.remove(item.jellyTween);
}
const t = time / 9;
const baseSX = item.scaleX;
const baseSY = item.scaleY;
let index = 0;
const run = () => {
if (index >= arr.length) {
item.jellyTween = null;
return;
}
const data = arr[index];
const t = tweenChange(item, {scaleX: data[0], scaleY: data[1]}, data[2], () => {
index ++;
run();
}, TWEEN.Easing.Sinusoidal.InOut);
item.jellyTween = t;
};
const arr = [
[baseSX * 1.1, baseSY * 0.9, t],
[baseSX * 0.98, baseSY * 1.02, t * 2],
[baseSX * 1.02, baseSY * 0.98, t * 2],
[baseSX * 0.99, baseSY * 1.01, t * 2],
[baseSX * 1.0, baseSY * 1.0, t * 2],
];
run();
}
export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen = 80, showTime = 0.4) {
for (let i = 0; i < num; i ++) {
const particle = new MySprite();
particle.init(img);
particle.x = pos.x;
particle.y = pos.y;
parent.addChild(particle);
const randomR = 360 * Math.random();
particle.rotation = randomR;
const randomS = 0.3 + Math.random() * 0.7;
particle.setScaleXY(randomS * 0.3);
const randomX = Math.random() * 20 - 10;
particle.x += randomX;
const randomY = Math.random() * 20 - 10;
particle.y += randomY;
const randomL = minLen + Math.random() * (maxLen - minLen);
const randomA = 360 * Math.random();
const randomT = getPosByAngle(randomA, randomL);
moveItem(particle, particle.x + randomT.x, particle.y + randomT.y, showTime, () => {
}, TWEEN.Easing.Exponential.Out);
// scaleItem(particle, 0, 0.6, () => {
//
// });
scaleItem(particle, randomS, 0.6, () => {
}, TWEEN.Easing.Exponential.Out);
setTimeout(() => {
hideItem(particle, 0.4, () => {
}, TWEEN.Easing.Cubic.In);
}, showTime * 0.5 * 1000);
}
}
export function shake(item, time = 0.5, callback = null, rate = 1) {
if (item.shakeTween) {
return;
}
item.shakeTween = true;
const offX = 15 * item.scaleX * rate;
const offY = 15 * item.scaleX * rate;
const baseX = item.x;
const baseY = item.y;
const easing = TWEEN.Easing.Sinusoidal.InOut;
const move4 = () => {
moveItem(item, baseX, baseY, time / 4, () => {
item.shakeTween = false;
if (callback) {
callback();
}
}, easing);
};
const move3 = () => {
moveItem(item, baseX + offX / 4, baseY + offY / 4, time / 4, () => {
move4();
}, easing);
};
const move2 = () => {
moveItem(item, baseX - offX / 4 * 3, baseY - offY / 4 * 3, time / 4, () => {
move3();
}, easing);
};
const move1 = () => {
moveItem(item, baseX + offX, baseY + offY, time / 7.5, () => {
move2();
}, easing);
};
move1();
drawSelf() {
super.drawSelf();
this.drawShape();
}
} }
// --------------- custom class --------------------
export class HotZoneItem extends MySprite { export class HotZoneItem extends MySprite {
lineDashFlag = false; lineDashFlag = false;
arrow: MySprite; arrow: MySprite;
label: Label; label: Label;
title; text;
arrowTop; arrowTop;
arrowRight; arrowRight;
audio_url;
pic_url;
text;
private _itemType;
private shapeRect: ShapeRect;
get itemType() {
return this._itemType;
}
set itemType(value) {
this._itemType = value;
}
setSize(w, h) { setSize(w, h) {
this.width = w; this.width = w;
this.height = h; this.height = h;
const rect = new ShapeRect(this.ctx); const rect = new ShapeRect(this.ctx);
rect.x = -w / 2; rect.x = -w / 2;
rect.y = -h / 2; rect.y = -h / 2;
rect.setSize(w, h); rect.setSize(w, h);
rect.fillColor = '#ffffff'; rect.fillColor = '#FFFFFF';
rect.alpha = 0.2; rect.alpha = 0.2;
this.addChild(rect); this.addChild(rect);
} }
showLabel(text = null) { showLabel(text = null) {
if (!this.label) { if (!this.label) {
this.label = new Label(this.ctx); this.label = new Label(this.ctx);
this.label.anchorY = 0; // this.label.anchorY = 0;
this.label.fontSize = 40; this.label.fontSize = '40px';
this.label.textAlign = 'center'; this.label.textAlign = 'center';
this.label.color = "#7a4250"
this.addChild(this.label); this.addChild(this.label);
// this.label.scaleX = 1 / this.scaleX;
// this.label.scaleY = 1 / this.scaleY;
this.refreshLabelScale(); this.refreshLabelScale();
} }
if (text) { if (text) {
this.label.text = text; this.label.text = text;
} else if (this.title) { } else if (this.text) {
this.label.text = this.title; this.label.text = this.text;
} }
this.label.visible = true; this.label.visible = true;
} }
hideLabel() { hideLabel() {
if (!this.label) { return; } if (!this.label) { return; }
this.label.visible = false; this.label.visible = false;
} }
...@@ -2030,29 +351,25 @@ export class HotZoneItem extends MySprite { ...@@ -2030,29 +351,25 @@ export class HotZoneItem extends MySprite {
this.arrow.visible = true; this.arrow.visible = true;
} else { } else {
this.arrow = new MySprite(this.ctx); this.arrow = new MySprite(this.ctx);
this.arrow.load('assets/common/arrow.png', 1, 0); this.arrow.load('assets/play/common/arrow.png', 1, 0);
this.arrow.setScaleXY(0.06); this.arrow.setScaleXY(0.06);
this.arrowTop = new MySprite(this.ctx); this.arrowTop = new MySprite(this.ctx);
this.arrowTop.load('assets/common/arrow_top.png', 0.5, 0); this.arrowTop.load('assets/play/common/arrow_top.png', 0.5, 0);
this.arrowTop.setScaleXY(0.06); this.arrowTop.setScaleXY(0.06);
this.arrowRight = new MySprite(this.ctx); this.arrowRight = new MySprite(this.ctx);
this.arrowRight.load('assets/common/arrow_right.png', 1, 0.5); this.arrowRight.load('assets/play/common/arrow_right.png', 1, 0.5);
this.arrowRight.setScaleXY(0.06); this.arrowRight.setScaleXY(0.06);
} }
this.showLabel(); this.showLabel();
} }
hideLineDash() { hideLineDash() {
this.lineDashFlag = false; this.lineDashFlag = false;
if (this.arrow) { if (this.arrow) {
this.arrow.visible = false; this.arrow.visible = false;
} }
this.hideLabel(); this.hideLabel();
} }
...@@ -2060,14 +377,11 @@ export class HotZoneItem extends MySprite { ...@@ -2060,14 +377,11 @@ export class HotZoneItem extends MySprite {
drawArrow() { drawArrow() {
if (!this.arrow) { return; } if (!this.arrow) { return; }
const rect = this.getBoundingBox(); const rect = this.getBoundingBox();
this.arrow.x = rect.x + rect.width; this.arrow.x = rect.x + rect.width;
this.arrow.y = rect.y; this.arrow.y = rect.y;
this.arrow.update(); this.arrow.update();
this.arrowTop.x = rect.x + rect.width / 2; this.arrowTop.x = rect.x + rect.width / 2;
this.arrowTop.y = rect.y; this.arrowTop.y = rect.y;
this.arrowTop.update(); this.arrowTop.update();
...@@ -2078,48 +392,28 @@ export class HotZoneItem extends MySprite { ...@@ -2078,48 +392,28 @@ export class HotZoneItem extends MySprite {
} }
drawFrame() { drawFrame() {
this.ctx.save(); this.ctx.save();
const rect = this.getBoundingBox(); const rect = this.getBoundingBox();
const w = rect.width; const w = rect.width;
const h = rect.height; const h = rect.height;
const x = rect.x + w / 2; const x = rect.x + w / 2;
const y = rect.y + h / 2; const y = rect.y + h / 2;
this.ctx.setLineDash([5, 5]); this.ctx.setLineDash([5, 5]);
this.ctx.lineWidth = 2; this.ctx.lineWidth = 2;
this.ctx.strokeStyle = '#1bfff7'; this.ctx.strokeStyle = '#1bfff7';
// this.ctx.fillStyle = '#ffffff';
this.ctx.beginPath(); this.ctx.beginPath();
this.ctx.moveTo( x - w / 2, y - h / 2); this.ctx.moveTo( x - w / 2, y - h / 2);
this.ctx.lineTo(x + w / 2, y - h / 2); this.ctx.lineTo(x + w / 2, y - h / 2);
this.ctx.lineTo(x + w / 2, y + h / 2); this.ctx.lineTo(x + w / 2, y + h / 2);
this.ctx.lineTo(x - w / 2, y + h / 2); this.ctx.lineTo(x - w / 2, y + h / 2);
this.ctx.lineTo(x - w / 2, y - h / 2); this.ctx.lineTo(x - w / 2, y - h / 2);
// this.ctx.fill();
this.ctx.stroke(); this.ctx.stroke();
this.ctx.restore(); this.ctx.restore();
} }
draw() { draw() {
super.draw(); super.draw();
if (this.lineDashFlag) { if (this.lineDashFlag) {
this.drawFrame(); this.drawFrame();
this.drawArrow(); this.drawArrow();
...@@ -2127,127 +421,310 @@ export class HotZoneItem extends MySprite { ...@@ -2127,127 +421,310 @@ export class HotZoneItem extends MySprite {
} }
} }
export class HotZoneImg extends MySprite {
drawFrame() {
this.ctx.save();
const rect = this.getBoundingBox();
const w = rect.width;
const h = rect.height;
const x = rect.x + w / 2;
const y = rect.y + h / 2;
this.ctx.setLineDash([5, 5]); export class HotZoneImageItem extends MySprite {
this.ctx.lineWidth = 2; index
this.ctx.strokeStyle = '#1bfff7'; lineDashFlag = false;
arrow: MySprite;
label: Label;
image: MySprite;
image_url: String;
labelBox: MySprite;
audio_url: String;
attImage_url: String;
text = "";
type = "text";
card_audio_url: String
scale
arrowTop;
arrowRight;
init(image_url = null, text?, type?, callback?, handleSave?){
let change = true;
if(type == this.type){
change = false
}
if(type && type=="Text"){
image_url = "assets/play/default/images/bg_50_50.png";
this.type = "Text"
}else if(!type){
this.type = "Text"
}
if(text){
this.text = text
}else{
this.text = ""
}
this.showImage(image_url, (img)=>{
callback && callback(img.width, img.height)
if(type == "Text"){
this.scaleX = 104 / img.width
this.scaleY = 78 / img.height
this.setSize(img.width*this.scaleX, img.height*this.scaleY)
}else{
this.setSize(img.width*this.image.scaleX, img.height*this.image.scaleY)
}
handleSave && handleSave()
this.lineDashFlag = true;
if(type == "Text"){
this.showLabel(text);
// this.arrow.visible = false
}else{
if(this.label){
this.removeChild(this.label)
}
this.drawArrow()
}
if(change){
this.showLineDash()
}
})
}
this.ctx.beginPath();
this.ctx.moveTo( x - w / 2, y - h / 2);
this.ctx.lineTo(x + w / 2, y - h / 2);
this.ctx.lineTo(x + w / 2, y + h / 2);
this.ctx.lineTo(x - w / 2, y + h / 2);
this.ctx.lineTo(x - w / 2, y - h / 2);
// this.ctx.fill(); initNew(callback?, handleSave?){
this.ctx.stroke(); if(this.type && this.type=="Text"){
this.image_url = "assets/play/default/images/bg_50_50.png";
}
this.showImage(this.image_url, (img)=>{
callback && callback(img.width, img.height)
if(this.type == "Text"){
this.scaleX = 104 / img.width
this.scaleY = 78 / img.height
this.setSize(104, 78)
}else{
this.setSize(img.width*this.image.scaleX, img.height*this.image.scaleY)
}
handleSave && handleSave()
this.lineDashFlag = true;
if(this.type == "Text"){
this.showLabel(this.text);
}else{
this.showLabel(this.index);
}
this.drawArrow()
this.showLineDash()
})
}
setSize(w, h) {
this.width = w;
this.height = h;
}
this.ctx.restore(); showLabel(text = null) {
if (!this.label) {
this.labelBox = new MySprite(this.ctx);
this.labelBox.load('assets/play/default/images/bg_50_50.png').then(()=>{
this.labelBox.x = this.width/2;
this.labelBox.y = this.height/2;
});
this.label = new Label(this.ctx);
this.label.fontSize = "45";
this.label.textAlign = 'center';
this.label.color = "#7A4250"
if(this.type == "Text"){
this.labelBox.visible = true
}else{
this.labelBox.visible = false
}
this.labelBox.addChild(this.label);
this.addChild(this.labelBox);
this.refreshLabelScale();
}
if (text) {
this.label.text = text;
} else if (this.text) {
this.label.text = this.text;
}
this.label.visible = true;
} }
draw() { hideLabel() {
super.draw(); if (!this.label) { return; }
this.label.visible = false;
}
this.drawFrame(); showImage(image_url = null, callback) {
this.loadImage(image_url).then((img)=>{
if(this.image){
this.removeChild(this.image)
}
this.image = new MySprite(this.ctx);
this.image.init(img)
this.image.x = this.image.width/2
this.image.y = this.image.height/2
this.image.alpha = 0.7;
this.image_url = image_url;
this.addChild(this.image,-1);
callback && callback(this.image)
})
} }
}
export class HotZoneLabel extends Label { loadImage(image_url = null){
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = image_url;
})
}
hideImage() {
if (!this.image) { return; }
this.image.visible = false;
}
drawFrame() { refreshLabelScale() {
this.labelBox.scaleX = 75 / (this.labelBox.width*this.image.scaleX)
}
this.ctx.save(); showLineDash() {
if (this.arrow) {
this.arrow.visible = true;
} else {
this.arrow = new MySprite(this.ctx);
this.arrow.load('assets/play/common/arrow.png', 1, 0);
this.arrow.setScaleXY(0.06);
const rect = this.getBoundingBox(); this.arrowTop = new MySprite(this.ctx);
const w = rect.width / this.scaleX; this.arrowTop.load('assets/play/common/arrow_top.png', 0.5, 0);
const h = this.height * this.scaleY; this.arrowTop.setScaleXY(0.06);
const x = this.x;
const y = this.y;
this.ctx.setLineDash([5, 5]); this.arrowRight = new MySprite(this.ctx);
this.ctx.lineWidth = 2; this.arrowRight.load('assets/play/common/arrow_right.png', 1, 0.5);
this.ctx.strokeStyle = '#1bfff7'; this.arrowRight.setScaleXY(0.06);
}
}
this.ctx.beginPath(); hideLineDash() {
this.ctx.moveTo( x - w / 2, y - h / 2); this.lineDashFlag = false;
this.ctx.lineTo(x + w / 2, y - h / 2); if (this.arrow) {
this.ctx.lineTo(x + w / 2, y + h / 2); this.arrow.visible = false;
this.ctx.lineTo(x - w / 2, y + h / 2); }
this.ctx.lineTo(x - w / 2, y - h / 2); this.hideLabel();
}
// this.ctx.fill(); drawArrow() {
this.ctx.stroke(); if(this.offSetCenter){
if (!this.arrow) { return; }
const rect = this.getBoundingBox();
this.arrow.x = rect.x + rect.width / 2;
this.arrow.y = rect.y - rect.height / 2;
this.arrow.update();
this.arrowTop.x = rect.x
this.arrowTop.y = rect.y - rect.height / 2;
this.arrowTop.update();
this.arrowRight.x = rect.x + rect.width / 2;
this.arrowRight.y = rect.y //+ rect.height / 2;
this.arrowRight.update();
}else{
if (!this.arrow) { return; }
const rect = this.getBoundingBox();
this.arrow.x = rect.x + rect.width;
this.arrow.y = rect.y;
this.arrow.update();
this.arrowTop.x = rect.x + rect.width / 2;
this.arrowTop.y = rect.y;
this.arrowTop.update();
this.arrowRight.x = rect.x + rect.width;
this.arrowRight.y = rect.y + rect.height / 2;
this.arrowRight.update();
}
}
this.ctx.restore(); drawFrame() {
if(this.offSetCenter){
this.ctx.save();
const rect = this.getBoundingBox();
const w = rect.width;
const h = rect.height;
const x = rect.x// + w / 2;
const y = rect.y// + h / 2;
this.ctx.setLineDash([5, 5]);
this.ctx.lineWidth = 2;
this.ctx.strokeStyle = '#1bfff7';
this.ctx.beginPath();
this.ctx.moveTo( x - w / 2, y - h / 2);
this.ctx.lineTo(x + w / 2, y - h / 2);
this.ctx.lineTo(x + w / 2, y + h / 2);
this.ctx.lineTo(x - w / 2, y + h / 2);
this.ctx.lineTo(x - w / 2, y - h / 2);
this.ctx.stroke();
this.ctx.restore();
}else{
this.ctx.save();
const rect = this.getBoundingBox();
const w = rect.width;
const h = rect.height;
const x = rect.x + w / 2;
const y = rect.y + h / 2;
this.ctx.setLineDash([5, 5]);
this.ctx.lineWidth = 2;
this.ctx.strokeStyle = '#1bfff7';
this.ctx.beginPath();
this.ctx.moveTo( x - w / 2, y - h / 2);
this.ctx.lineTo(x + w / 2, y - h / 2);
this.ctx.lineTo(x + w / 2, y + h / 2);
this.ctx.lineTo(x - w / 2, y + h / 2);
this.ctx.lineTo(x - w / 2, y - h / 2);
this.ctx.stroke();
this.ctx.restore();
}
} }
draw() { draw() {
super.draw(); super.draw();
if (this.lineDashFlag) {
this.drawFrame(); this.drawFrame();
this.drawArrow();
}
} }
} }
export class EditorItem extends MySprite { export class EditorItem extends MySprite {
lineDashFlag = false; lineDashFlag = false;
arrow: MySprite; arrow: MySprite;
label: Label; label:Label;
text; text;
showLabel(text = null) { showLabel(text = null) {
if (!this.label) { if (!this.label) {
this.label = new Label(this.ctx); this.label = new Label(this.ctx);
this.label.anchorY = 0; this.label.anchorY = 0;
this.label.fontSize = 50; this.label.fontSize = '50px';
this.label.textAlign = 'center'; this.label.textAlign = 'center';
this.addChild(this.label); this.addChild(this.label);
this.label.setScaleXY(1 / this.scaleX); this.label.setScaleXY(1 / this.scaleX);
} }
this.label.text = this.text;
if (text) {
this.label.text = text;
} else if (this.text) {
this.label.text = this.text;
}
this.label.visible = true; this.label.visible = true;
} }
hideLabel() { hideLabel() {
if (!this.label) { return; } if (!this.label) { return; }
this.label.visible = false; this.label.visible = false;
} }
showLineDash() { showLineDash() {
this.lineDashFlag = true; this.lineDashFlag = true;
if (this.arrow) { if (this.arrow) {
this.arrow.visible = true; this.arrow.visible = true;
} else { } else {
this.arrow = new MySprite(this.ctx); this.arrow = new MySprite(this.ctx);
this.arrow.load('assets/common/arrow.png', 1, 0); this.arrow.load('assets/play/common/arrow.png', 1, 0);
this.arrow.setScaleXY(0.06); this.arrow.setScaleXY(0.06);
} }
this.showLabel(); this.showLabel();
} }
...@@ -2326,783 +803,89 @@ export class EditorItem extends MySprite { ...@@ -2326,783 +803,89 @@ export class EditorItem extends MySprite {
// export class Label extends MySprite {
//
// import TWEEN from '@tweenjs/tween.js'; text:String;
// fontSize:String = '40px';
// fontName:String = 'Verdana';
// class Sprite { textAlign:String = 'left';
// x = 0;
// y = 0;
// color = ''; constructor(ctx) {
// radius = 0; super(ctx);
// alive = false; this.init();
// margin = 0; }
// angle = 0;
// ctx; drawText() {
//
// constructor(ctx) { if (!this.text) { return; }
// this.ctx = ctx;
// } this.ctx.font = `${this.fontSize} ${this.fontName}`;
// update($event) { this.ctx.textAlign = this.textAlign;
// this.draw(); this.ctx.textBaseline = 'middle';
// } this.ctx.fontWeight = 900;
// draw() {
// // this.ctx.lineWidth = 5;
// } // this.ctx.strokeStyle = '#ffffff';
// // this.ctx.strokeText(this.text, 0, 0);
// }
// this.ctx.fillStyle = '#7a4250';
// this.ctx.fillText(this.text, 0, 0);
//
// }
//
// export class MySprite extends Sprite {
// drawSelf() {
// width = 0; super.drawSelf();
// height = 0; this.drawText();
// _anchorX = 0; }
// _anchorY = 0;
// _offX = 0; }
// _offY = 0;
// scaleX = 1;
// scaleY = 1;
// alpha = 1; export function getPosByAngle(angle, len) {
// rotation = 0;
// visible = true; const radian = angle * Math.PI / 180;
// const x = Math.sin(radian) * len;
// children = [this]; const y = Math.cos(radian) * len;
//
// img; return {x, y};
// _z = 0;
// }
//
// init(imgObj = null, anchorX:number = 0.5, anchorY:number = 0.5) { export function getAngleByPos(px, py, mx, my) {
//
// if (imgObj) { const x = Math.abs(px - mx);
// const y = Math.abs(py - my);
// this.img = imgObj; const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
// const cos = y / z;
// this.width = this.img.width; const radina = Math.acos(cos); // 用反三角函数求弧度
// this.height = this.img.height; let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度
// }
// if(mx > px && my > py) {// 鼠标在第四象限
// this.anchorX = anchorX; angle = 180 - angle;
// this.anchorY = anchorY; }
// }
// if(mx === px && my > py) {// 鼠标在y轴负方向上
// angle = 180;
// }
// update($event = null) {
// if (this.visible) { if(mx > px && my === py) {// 鼠标在x轴正方向上
// this.draw(); angle = 90;
// } }
// }
// draw() { if(mx < px && my > py) {// 鼠标在第三象限
// angle = 180 + angle;
// this.ctx.save(); }
//
// this.drawInit(); if(mx < px && my === py) {// 鼠标在x轴负方向
// angle = 270;
// this.updateChildren(); }
//
// this.ctx.restore(); if(mx < px && my < py) {// 鼠标在第二象限
// } angle = 360 - angle;
// }
// drawInit() {
// return angle;
// this.ctx.translate(this.x, this.y); }
//
// this.ctx.rotate(this.rotation * Math.PI / 180);
//
// this.ctx.scale(this.scaleX, this.scaleY);
//
// this.ctx.globalAlpha = this.alpha;
//
// }
//
// drawSelf() {
// if (this.img) {
// this.ctx.drawImage(this.img, this._offX, this._offY);
// }
// }
//
// updateChildren() {
//
// if (this.children.length <= 0) { return; }
//
// for (let i = 0; i < this.children.length; i++) {
//
// if (this.children[i] === this) {
//
// this.drawSelf();
// } else {
//
// this.children[i].update();
// }
// }
// }
//
//
// load(url, anchorX = 0.5, anchorY = 0.5) {
//
// return new Promise((resolve, reject) => {
// const img = new Image();
// img.onload = () => resolve(img);
// img.onerror = reject;
// img.src = url;
// }).then(img => {
//
// this.init(img, anchorX, anchorY);
// return img;
// });
// }
//
// addChild(child, z = 1) {
// if (this.children.indexOf(child) === -1) {
// this.children.push(child);
// child._z = z;
// child.parent = this;
// }
//
// this.children.sort((a, b) => {
// return a._z - b._z;
// });
//
// }
// removeChild(child) {
// const index = this.children.indexOf(child);
// if (index !== -1) {
// this.children.splice(index, 1);
// }
// }
//
// set anchorX(value) {
// this._anchorX = value;
// this.refreshAnchorOff();
// }
// get anchorX() {
// return this._anchorX;
// }
// set anchorY(value) {
// this._anchorY = value;
// this.refreshAnchorOff();
// }
// get anchorY() {
// return this._anchorY;
// }
// refreshAnchorOff() {
// this._offX = -this.width * this.anchorX;
// this._offY = -this.height * this.anchorY;
// }
//
// setScaleXY(value) {
// this.scaleX = this.scaleY = value;
// }
//
// getBoundingBox() {
//
// const x = this.x + this._offX * this.scaleX;
// const y = this.y + this._offY * this.scaleY;
// const width = this.width * this.scaleX;
// const height = this.height * this.scaleY;
//
// return {x, y, width, height};
// }
//
// }
//
//
//
//
//
// export class Item extends MySprite {
//
// baseX;
//
// move(targetY, callBack) {
//
// const self = this;
//
// const tween = new TWEEN.Tween(this)
// .to({ y: targetY }, 2500)
// .easing(TWEEN.Easing.Quintic.Out)
// .onComplete(function() {
//
// self.hide(callBack);
// // if (callBack) {
// // callBack();
// // }
// })
// .start();
//
// }
//
// show(callBack = null) {
//
// const tween = new TWEEN.Tween(this)
// .to({ alpha: 1 }, 800)
// // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
// .onComplete(function() {
// if (callBack) {
// callBack();
// }
// })
// .start(); // Start the tween immediately.
//
// }
//
// hide(callBack = null) {
//
// const tween = new TWEEN.Tween(this)
// .to({ alpha: 0 }, 800)
// // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
// .onComplete(function() {
// if (callBack) {
// callBack();
// }
// })
// .start(); // Start the tween immediately.
// }
//
//
// shake(id) {
//
//
// if (!this.baseX) {
// this.baseX = this.x;
// }
//
// const baseX = this.baseX;
// const baseTime = 50;
// const sequence = [
// {target: {x: baseX + 40 * id}, time: baseTime - 25},
// {target: {x: baseX - 20 * id}, time: baseTime},
// {target: {x: baseX + 10 * id}, time: baseTime},
// {target: {x: baseX - 5 * id}, time: baseTime},
// {target: {x: baseX + 2 * id}, time: baseTime},
// {target: {x: baseX - 1 * id}, time: baseTime},
// {target: {x: baseX}, time: baseTime},
//
// ];
//
//
// const self = this;
//
// function runSequence() {
//
// if (self['shakeTween']) {
// self['shakeTween'].stop();
// }
//
// const tween = new TWEEN.Tween(self);
//
// if (sequence.length > 0) {
// // console.log('sequence.length: ', sequence.length);
// const action = sequence.shift();
// tween.to(action['target'], action['time']);
// tween.onComplete( () => {
// runSequence();
// });
// tween.start();
//
// self['shakeTween'] = tween;
// }
// }
//
// runSequence();
//
// }
//
//
//
// drop(targetY, callBack = null) {
//
// const self = this;
//
// const time = Math.abs(targetY - this.y) * 2.4;
//
// this.alpha = 1;
//
// const tween = new TWEEN.Tween(this)
// .to({ y: targetY }, time)
// .easing(TWEEN.Easing.Cubic.In)
// .onComplete(function() {
//
// // self.hideItem(callBack);
// if (callBack) {
// callBack();
// }
// })
// .start();
//
//
// }
//
//
// }
//
//
// export class EndSpr extends MySprite {
//
// show(s) {
//
// this.scaleX = this.scaleY = 0;
// this.alpha = 0;
//
// const tween = new TWEEN.Tween(this)
// .to({ alpha: 1, scaleX: s, scaleY: s }, 800)
// .easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
// .onComplete(function() {
//
// })
// .start(); // Start the tween immediately.
//
// }
// }
//
//
//
// export class ShapeRect extends MySprite {
//
// fillColor = '#FF0000';
//
// setSize(w, h) {
// this.width = w;
// this.height = h;
//
// console.log('w:', w);
// console.log('h:', h);
// }
//
// drawShape() {
//
// this.ctx.fillStyle = this.fillColor;
// this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
//
// }
//
//
// drawSelf() {
// super.drawSelf();
// this.drawShape();
// }
// }
//
//
// export class HotZoneItem extends MySprite {
//
//
// lineDashFlag = false;
// arrow: MySprite;
// label: Label;
// title;
//
// arrowTop;
// arrowRight;
//
// audio_url;
// pic_url;
// text;
// private _itemType;
// private shapeRect: ShapeRect;
//
// get itemType() {
// return this._itemType;
// }
// set itemType(value) {
// this._itemType = value;
// }
//
// setSize(w, h) {
// this.width = w;
// this.height = h;
//
//
// const rect = new ShapeRect(this.ctx);
// rect.x = -w / 2;
// rect.y = -h / 2;
// rect.setSize(w, h);
// rect.fillColor = '#ffffff';
// rect.alpha = 0.2;
// this.addChild(rect);
// }
//
// showLabel(text = null) {
//
//
// if (!this.label) {
// this.label = new Label(this.ctx);
// this.label.anchorY = 0;
// this.label.fontSize = '40px';
// this.label.textAlign = 'center';
// this.addChild(this.label);
// // this.label.scaleX = 1 / this.scaleX;
// // this.label.scaleY = 1 / this.scaleY;
//
// this.refreshLabelScale();
//
// }
//
// if (text) {
// this.label.text = text;
// } else if (this.title) {
// this.label.text = this.title;
// }
// this.label.visible = true;
//
// }
//
// hideLabel() {
// if (!this.label) { return; }
//
// this.label.visible = false;
// }
//
// refreshLabelScale() {
// if (this.scaleX == this.scaleY) {
// this.label.setScaleXY(1);
// }
//
// if (this.scaleX > this.scaleY) {
// this.label.scaleX = this.scaleY / this.scaleX;
// } else {
// this.label.scaleY = this.scaleX / this.scaleY;
// }
// }
//
// showLineDash() {
// this.lineDashFlag = true;
//
// if (this.arrow) {
// this.arrow.visible = true;
// } else {
// this.arrow = new MySprite(this.ctx);
// this.arrow.load('assets/common/arrow.png', 1, 0);
// this.arrow.setScaleXY(0.06);
//
// this.arrowTop = new MySprite(this.ctx);
// this.arrowTop.load('assets/common/arrow_top.png', 0.5, 0);
// this.arrowTop.setScaleXY(0.06);
//
// this.arrowRight = new MySprite(this.ctx);
// this.arrowRight.load('assets/common/arrow_right.png', 1, 0.5);
// this.arrowRight.setScaleXY(0.06);
// }
//
// this.showLabel();
// }
//
// hideLineDash() {
//
// this.lineDashFlag = false;
//
// if (this.arrow) {
// this.arrow.visible = false;
// }
//
// this.hideLabel();
// }
//
//
//
// drawArrow() {
// if (!this.arrow) { return; }
//
// const rect = this.getBoundingBox();
// this.arrow.x = rect.x + rect.width;
// this.arrow.y = rect.y;
//
// this.arrow.update();
//
//
// this.arrowTop.x = rect.x + rect.width / 2;
// this.arrowTop.y = rect.y;
// this.arrowTop.update();
//
// this.arrowRight.x = rect.x + rect.width;
// this.arrowRight.y = rect.y + rect.height / 2;
// this.arrowRight.update();
// }
//
// drawFrame() {
//
//
// this.ctx.save();
//
//
// const rect = this.getBoundingBox();
//
// const w = rect.width;
// const h = rect.height;
// const x = rect.x + w / 2;
// const y = rect.y + h / 2;
//
// this.ctx.setLineDash([5, 5]);
// this.ctx.lineWidth = 2;
// this.ctx.strokeStyle = '#1bfff7';
// // this.ctx.fillStyle = '#ffffff';
//
// this.ctx.beginPath();
//
// this.ctx.moveTo( x - w / 2, y - h / 2);
//
// this.ctx.lineTo(x + w / 2, y - h / 2);
//
// this.ctx.lineTo(x + w / 2, y + h / 2);
//
// this.ctx.lineTo(x - w / 2, y + h / 2);
//
// this.ctx.lineTo(x - w / 2, y - h / 2);
//
// // this.ctx.fill();
// this.ctx.stroke();
//
//
//
//
// this.ctx.restore();
//
// }
//
// draw() {
// super.draw();
//
// if (this.lineDashFlag) {
// this.drawFrame();
// this.drawArrow();
// }
// }
// }
//
//
// export class EditorItem extends MySprite {
//
// lineDashFlag = false;
// arrow: MySprite;
// label:Label;
// text;
//
// showLabel(text = null) {
//
//
// if (!this.label) {
// this.label = new Label(this.ctx);
// this.label.anchorY = 0;
// this.label.fontSize = '50px';
// this.label.textAlign = 'center';
// this.addChild(this.label);
// this.label.setScaleXY(1 / this.scaleX);
// }
//
// if (text) {
// this.label.text = text;
// } else if (this.text) {
// this.label.text = this.text;
// }
// this.label.visible = true;
//
// }
//
// hideLabel() {
// if (!this.label) { return; }
//
// this.label.visible = false;
// }
//
// showLineDash() {
// this.lineDashFlag = true;
//
// if (this.arrow) {
// this.arrow.visible = true;
// } else {
// this.arrow = new MySprite(this.ctx);
// this.arrow.load('assets/common/arrow.png', 1, 0);
// this.arrow.setScaleXY(0.06);
//
// }
//
// this.showLabel();
// }
//
// hideLineDash() {
//
// this.lineDashFlag = false;
//
// if (this.arrow) {
// this.arrow.visible = false;
// }
//
// this.hideLabel();
// }
//
//
//
// drawArrow() {
// if (!this.arrow) { return; }
//
// const rect = this.getBoundingBox();
// this.arrow.x = rect.x + rect.width;
// this.arrow.y = rect.y;
//
// this.arrow.update();
// }
//
// drawFrame() {
//
//
// this.ctx.save();
//
//
// const rect = this.getBoundingBox();
//
// const w = rect.width;
// const h = rect.height;
// const x = rect.x + w / 2;
// const y = rect.y + h / 2;
//
// this.ctx.setLineDash([5, 5]);
// this.ctx.lineWidth = 2;
// this.ctx.strokeStyle = '#1bfff7';
// // this.ctx.fillStyle = '#ffffff';
//
// this.ctx.beginPath();
//
// this.ctx.moveTo( x - w / 2, y - h / 2);
//
// this.ctx.lineTo(x + w / 2, y - h / 2);
//
// this.ctx.lineTo(x + w / 2, y + h / 2);
//
// this.ctx.lineTo(x - w / 2, y + h / 2);
//
// this.ctx.lineTo(x - w / 2, y - h / 2);
//
// // this.ctx.fill();
// this.ctx.stroke();
//
//
//
//
// this.ctx.restore();
//
// }
//
// draw() {
// super.draw();
//
// if (this.lineDashFlag) {
// this.drawFrame();
// this.drawArrow();
// }
// }
// }
//
//
//
// export class Label extends MySprite {
//
// text:String;
// fontSize:String = '40px';
// fontName:String = 'Verdana';
// textAlign:String = 'left';
//
//
// constructor(ctx) {
// super(ctx);
// this.init();
// }
//
// drawText() {
//
// // console.log('in drawText', this.text);
//
// if (!this.text) { return; }
//
// this.ctx.font = `${this.fontSize} ${this.fontName}`;
// this.ctx.textAlign = this.textAlign;
// this.ctx.textBaseline = 'middle';
// this.ctx.fontWeight = 900;
//
// this.ctx.lineWidth = 5;
// this.ctx.strokeStyle = '#ffffff';
// this.ctx.strokeText(this.text, 0, 0);
//
// this.ctx.fillStyle = '#000000';
// this.ctx.fillText(this.text, 0, 0);
//
//
// }
//
//
// drawSelf() {
// super.drawSelf();
// this.drawText();
// }
//
// }
//
//
//
// export function getPosByAngle(angle, len) {
//
// const radian = angle * Math.PI / 180;
// const x = Math.sin(radian) * len;
// const y = Math.cos(radian) * len;
//
// return {x, y};
//
// }
//
// export function getAngleByPos(px, py, mx, my) {
//
// // const _x = p2x - p1x;
// // const _y = p2y - p1y;
// // const tan = _y / _x;
// //
// // const radina = Math.atan(tan); // 用反三角函数求弧度
// // const angle = Math.floor(180 / (Math.PI / radina)); //
// //
// // console.log('r: ' , angle);
// // return angle;
// //
//
//
//
// const x = Math.abs(px - mx);
// const y = Math.abs(py - my);
// // const x = Math.abs(mx - px);
// // const y = Math.abs(my - py);
// const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
// const cos = y / z;
// const radina = Math.acos(cos); // 用反三角函数求弧度
// let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度
//
// if(mx > px && my > py) {// 鼠标在第四象限
// angle = 180 - angle;
// }
//
// if(mx === px && my > py) {// 鼠标在y轴负方向上
// angle = 180;
// }
//
// if(mx > px && my === py) {// 鼠标在x轴正方向上
// angle = 90;
// }
//
// if(mx < px && my > py) {// 鼠标在第三象限
// angle = 180 + angle;
// }
//
// if(mx < px && my === py) {// 鼠标在x轴负方向
// angle = 270;
// }
//
// if(mx < px && my < py) {// 鼠标在第二象限
// angle = 360 - angle;
// }
//
// // console.log('angle: ', angle);
// return angle;
//
// }
<div class="p-image-children-editor"> <div class="p-image-children-editor">
<h5 style="margin-left: 2.5%;"> preview: </h5> <div style=" margin: 0 auto; width: 800px;">
<h5 style="margin-left: 2.5%;">预览:</h5>
<div class="preview-box" #wrap> <div id="canvas-container" style="margin:5px;">
<canvas id="canvas" #canvas></canvas> <div class="preview-box" #wrap style="margin-bottom: 20px">
</div> <canvas id="canvas" #canvas></canvas>
<div nz-row nzType="flex" nzAlign="middle">
<div nz-col nzSpan="5" nzOffset="1">
<h5> add background: </h5>
<div class="bg-box">
<app-upload-image-with-preview
[picUrl]="bgItem?.url"
(imageUploaded)="onBackgroundUploadSuccess($event)">
</app-upload-image-with-preview>
</div> </div>
</div> </div>
<div style="width: 100%;">
<!-- <div class="bg-box">
<app-upload-image-with-preview [picUrl]="bgItem.url" (imageUploaded)="onBackgroundUploadSuccess($event)">
</app-upload-image-with-preview>
</div> -->
<div style="display: flex; margin-bottom: 28px;">
<div style="flex: 1;" >
旋转:
</div>
<div style="flex: 5;" >
<nz-select [(ngModel)]="currentSelected" nzAllowClear style="min-width: 200px;" >
<nz-option *ngFor="let it of hotZoneArr; let i = index" [nzValue]="it" [nzLabel]="(i+1) + ' - ' + it.text"></nz-option>
</nz-select>
</div>
</div>
<div nz-col nzSpan="5" nzOffset="1" class="img-box" <div *ngIf="currentSelected" style="display: flex; margin-bottom: 28px;">
*ngFor="let it of hotZoneArr; let i = index"> <div style="flex: 5; display: flex;" >
<div style="flex:2; margin-right: 5px;">
<div <nz-input-group nzAddOnBefore="X:">
style="margin: auto; padding: 5px; margin-top: 30px; width:90%; border: 2px dashed #ddd; border-radius: 10px"> <nz-input-number [(ngModel)]="currentSelected.x" (ngModelChange)="autoSave()" ></nz-input-number>
<span style="margin-left: 40%;"> item-{{i + 1}} </nz-input-group>
</span> </div>
<button style="float: right;" nz-button nzType="danger" nzSize="small" (click)="deleteBtnClick(i)"> <div style="flex:2; margin-right: 5px;">
X <nz-input-group nzAddOnBefore="Y:">
<nz-input-number [(ngModel)]="currentSelected.y" (ngModelChange)="autoSave()" ></nz-input-number>
</nz-input-group>
</div>
<div style="flex:2; margin-right: 10px;">
<nz-input-group nzAddOnBefore="Rotation:" >
<nz-input-number [nzMin]="-180" [nzMax]="180" [(ngModel)]="currentSelected.rotation" (ngModelChange)="autoSave()" ></nz-input-number>
</nz-input-group>
</div>
<div style="flex:4;">
<nz-slider [nzMin]="-180" [nzMax]="180" [(ngModel)]="currentSelected.rotation" (nzOnAfterChange)="autoSave()" ></nz-slider>
</div>
</div>
</div>
<div style="text-align: center;">
<button nz-button nzType="primary" [nzSize]="'small'" nzShape="round" (click)="saveClick()"
[disabled]="!hotZoneChanged">
<i nz-icon type="save"></i>
Save
</button> </button>
</div>
<nz-divider style="margin-top: 10px;"></nz-divider> </div>
</div>
<div style="margin-top: -20px; margin-bottom: 5px"> <div>
<nz-radio-group [ngModel]="it.itemType" (ngModelChange)="radioChange($event, it)"> <div nzAlign="middle">
<label *ngIf="isHasRect" nz-radio nzValue="rect">矩形</label> <div class="img-box clearfix" style="border-bottom: 1px solid #DDD; padding-bottom: 10px;">
<label *ngIf="isHasPic" nz-radio nzValue="pic">图片</label> <div style="float: left; width: 100px;">
<label *ngIf="isHasText" nz-radio nzValue="text">文本</label> <h3>题号</h3>
</nz-radio-group> <input type="text" nz-input placeholder="" [(ngModel)]="bgItem.title.NO" (blur)="autoSave()" />
</div> </div>
<div style="float: left; width: 300px; margin-left: 50px;">
<div *ngIf="it.itemType == 'pic'"> <h3>课件标题</h3>
<app-upload-image-with-preview <input type="text" nz-input placeholder="" [(ngModel)]="bgItem.title.mainText" (blur)="autoSave()" />
[picUrl]="it?.pic_url"
(imageUploaded)="onItemImgUploadSuccess($event, it)">
</app-upload-image-with-preview>
</div> </div>
<div style="float: left; width: 300px; margin-left: 50px;">
<div *ngIf="it.itemType == 'text'"> <h3>标题发音</h3>
<input type="text" nz-input [(ngModel)]="it.text" (blur)="saveText(it)"> <app-audio-recorder id="index_audio_1" [audioUrl]="bgItem.title.mainTitleAudio" (audioUploaded)="onUploadSuccessByItem($event, bgItem.title,'mainTitleAudio', 'audio')" > </app-audio-recorder>
</div> </div>
<div style="float: left; width: 300px;">
<div style="width: 100%; margin-top: 5px;"> <h3>白板标题</h3>
<app-audio-recorder <input type="text" nz-input placeholder="" [(ngModel)]="bgItem.title.boardTitle" (blur)="autoSave()" />
[audioUrl]="it.audio_url"
(audioUploaded)="onItemAudioUploadSuccess($event, it)"
></app-audio-recorder>
</div> </div>
<div style="float: left; width: 300px; margin-left: 50px;">
<h3>白板标题发音</h3>
<app-audio-recorder id="index_audio_1" [audioUrl]="bgItem.title.boardTitleAudio" (audioUploaded)="onUploadSuccessByItem($event, bgItem.title,'boardTitleAudio', 'audio')" > </app-audio-recorder>
</div>
<!-- <div style="float: left; width: 300px; margin-left: 50px;">
<h3>题目长音频</h3>
<app-audio-recorder id="index_audio_1" [audioUrl]="bgItem.title.mainAudio" (audioUploaded)="onUploadSuccessByItem($event, bgItem.title,'mainAudio', 'audio')" > </app-audio-recorder>
</div> -->
</div> </div>
</div> </div>
<div style="border-right: 1px solid #DDD; display: flex; flex-direction: column;" >
<div class="img-box clearfix" *ngFor="let it of hotZoneArr; let i = index" style="border-bottom: 1px solid #DDD; padding-bottom: 10px; flex: 1; min-width: 800px;">
<div>
<h2> 词组-{{ i + 1 }}</h2>
</div>
<div style="position: relative; display: flex; ">
<div style="flex: 6; display: flex; flex-direction: column;">
<div style="flex: 1; display: flex; margin-bottom: 28px;" >
<div style="flex: 1;" >
文字:
</div>
<div style="flex: 5;" >
<input type="text" nz-input placeholder="" [(ngModel)]="it.text" (blur)="autoSave()" />
</div>
</div>
<div style="flex: 1; display: flex; margin-bottom: 28px;">
<div style="flex: 1;" >
音频:
</div>
<div style="flex: 5;" >
<app-audio-recorder [audioUrl]="it.audio_url" (audioUploaded)="onUploadSuccessByItem($event, it, 'audio_url', 'audio')" ></app-audio-recorder>
</div>
</div>
</div>
<div style="flex:1; margin-left: 10px;">
图片:
</div>
<div style="flex:4">
<div style="width:200px">
<app-upload-image-with-preview [picUrl]="it.image_url" (imageUploaded)="onUploadSuccessByItem($event, it, 'image_url', 'image')"></app-upload-image-with-preview>
</div>
</div>
<div style="flex:1; margin-left: 10px;">
附图:
</div>
<div style="flex:4">
<div style="width:200px">
<app-upload-image-with-preview [picUrl]="it.attImage_url" (imageUploaded)="onUploadSuccessByItem($event, it, 'attImage_url', 'image')"></app-upload-image-with-preview>
</div>
</div>
</div>
<div style="flex: 1; margin-bottom: 28px;">
<div style="float: left; width: 650px; display: flex;" >
<div style="flex:2; margin-right: 5px;">
<nz-input-group nzAddOnBefore="X:">
<nz-input-number [(ngModel)]="it.x" (ngModelChange)="autoSave()" ></nz-input-number>
</nz-input-group>
</div>
<div style="flex:2; margin-right: 5px;">
<nz-input-group nzAddOnBefore="Y:">
<nz-input-number [(ngModel)]="it.y" (ngModelChange)="autoSave()" ></nz-input-number>
</nz-input-group>
</div>
<div style="flex:2; margin-right: 10px;">
<nz-input-group nzAddOnBefore="Rotation:" >
<nz-input-number [nzMin]="-180" [nzMax]="180" [(ngModel)]="it.rotation" (ngModelChange)="autoSave()" ></nz-input-number>
</nz-input-group>
</div>
<div style="flex:1;">
<button style="flex:1; margin-bottom: 5px;" nz-button (click)="copyPositionData(it)">
<i nz-icon nzType="copy" nzTheme="outline"></i>
复制
</button>
</div>
<div style="flex:1;">
<button style="flex:1; margin-bottom: 5px;" (click)="showPasteModal(it)" nz-button>
<i nz-icon nzType="form" nzTheme="outline"></i>
黏贴
</button>
</div>
</div>
<div style="flex: 1 ; display: flex;" ></div>
</div>
<div nz-col nzSpan="5" nzOffset="1"> <div style="float: right; display: flex; margin-top: 5px; margin-right: 40px; ">
<!-- <button style="flex:1; margin-bottom: 5px;" nz-button nzType="dashed" (click)="handleMoveItemUp($event, i)"
<div class="bg-box"> [disabled]="i==0">
<button nz-button nzType="dashed" (click)="addBtnClick()" <i nz-icon nzType="up" nzTheme="outline"></i>
class="add-btn"> 上移
</button>
<button style="flex:1; margin-bottom: 5px;" nz-button nzType="dashed" (click)="handleMoveItemDown($event, i)"
[disabled]="i==hotZoneArr.length-1">
<i nz-icon nzType="down" nzTheme="outline"></i>
下移
</button> -->
<button style="flex:1; margin-bottom: 5px;" nz-button nzType="danger" (click)="deleteItem(hotZoneArr, i)">
<i nz-icon nzType="delete" nzTheme="outline"></i>
删除
</button>
</div>
</div>
<div *ngIf="hotZoneArr.length<8">
<button nz-button nzType="dashed" (click)="addBtnClick(hotZoneArr)" class="add-btn" style="margin:0 auto" >
<i nz-icon nzType="plus-circle" nzTheme="outline"></i> <i nz-icon nzType="plus-circle" nzTheme="outline"></i>
<!--Add Image--> 新建词组
Add hot zone
</button> </button>
</div> </div>
</div> </div>
</div> </div>
<nz-divider></nz-divider> <nz-divider></nz-divider>
<div class="save-box"> <div class="save-box">
<button class="save-btn" nz-button nzType="primary" [nzSize]="'large'" nzShape="round"
(click)="saveClick()" >
<i nz-icon nzType="save"></i>
Save
</button>
</div> </div>
<nz-modal [(nzVisible)]="showModalWindow" nzTitle="坐标粘贴" (nzOnCancel)="handlePasteCancle()" (nzOnOk)="handlePasteOk()" ng-paste="alert('d')">
</div> <textarea #pasteDataContainer rows="4" nz-input [(ngModel)]="pasteData"></textarea>
</nz-modal>
</div>
<label style="opacity: 0; position: absolute; top: 0px; font-family: 'BRLNSR_1'">1</label> \ No newline at end of file
.p-image-children-editor { .p-image-children-editor {
width: 100%; width: 100%;
height: 100%; height: 100%;
border-radius: 0.5rem; border-radius: 0.5rem;
min-width: 1200px;
border: 2px solid #ddd; border: 2px solid #ddd;
.preview-box { .preview-box {
margin: auto; margin: auto;
width: 95%; width: 100%;
height: 35vw; // height: 35vw;
border: 2px dashed #ddd; border: 2px dashed #ddd;
border-radius: 0.5rem; border-radius: 0.5rem;
background-color: #fafafa; background-color: #fafafa;
text-align: center; text-align: center;
color: #aaa; color: #aaa;
.preview-img { .preview-img {
height: 100%; height: 100%;
width: auto; width: auto;
} }
} }
.bg-box {
.bg-box{
//width: 100%;
margin-bottom: 1rem; margin-bottom: 1rem;
}
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
} }
.img-box { .img-box {
margin-bottom: 1rem; margin: 1rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
} }
.img-box-upload{ .img-box-upload {
width: 80%; width: 120px;
height: 80px;
} }
.add-btn { .add-btn {
margin-top: 1rem; margin-top: 1rem;
width: 200px; width: 200px;
height: 90px; height: 90px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
} }
} }
.save-box { .save-box {
width: 100%; width: 100%;
...@@ -85,28 +72,6 @@ h5 { ...@@ -85,28 +72,6 @@ h5 {
margin-top: 1rem; margin-top: 1rem;
} }
@font-face
{
font-family: 'BRLNSR_1';
src: url("/assets/font/BRLNSR_1.TTF") ;
}
//@import '../../../style/common_mixin'; //@import '../../../style/common_mixin';
// //
//.p-image-uploader { //.p-image-uploader {
......
import { import { Component, ElementRef, EventEmitter, HostListener, Input, OnChanges, OnDestroy, OnInit, Output, ViewChild } from '@angular/core';
Component, import {NzMessageService, NzNotificationService, UploadFile} from 'ng-zorro-antd';
ElementRef, import { Subject } from 'rxjs';
EventEmitter, import { debounceTime } from 'rxjs/operators';
HostListener, import { EditorItem, HotZoneImageItem, Label, MySprite } from './Unit';
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
ViewChild
} from '@angular/core';
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import {EditorItem, HotZoneImg, HotZoneItem, HotZoneLabel, Label, MySprite, removeItemFromArr} from './Unit';
import TWEEN from '@tweenjs/tween.js'; import TWEEN from '@tweenjs/tween.js';
import {getMinScale} from "../../play/Unit";
import {tar} from "compressing";
@Component({ @Component({
...@@ -24,281 +12,305 @@ import {tar} from "compressing"; ...@@ -24,281 +12,305 @@ import {tar} from "compressing";
styleUrls: ['./custom-hot-zone.component.scss'] styleUrls: ['./custom-hot-zone.component.scss']
}) })
export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
_bgItem = null;
@Input()
set bgItem(v) {
this._bgItem = v;
this.init();
}
get bgItem() {
return this._bgItem;
}
@Input() @Input()
imgItemArr = null; imgItemArr = null;
@Input() @Input()
hotZoneItemArr = null; hotZoneItemArr = null;
@Input() @Input()
hotZoneArr = null; hotZoneArr = null;
@Output() @Output()
save = new EventEmitter(); save = new EventEmitter();
@ViewChild('canvas', {static: true}) canvas: ElementRef;
@ViewChild('wrap', {static: true}) wrap: ElementRef;
@Input() @ViewChild('canvas') canvas: ElementRef;
isHasRect = true; @ViewChild('wrap') wrap: ElementRef;
@Input() @ViewChild('pasteDataContainer') pasteDataContainer: ElementRef;
isHasPic = true;
@Input()
isHasText = true;
@Input()
hotZoneFontObj = {
size: 50,
name: 'BRLNSR_1',
color: '#8f3758'
}
@Input()
defaultItemType = 'text';
@Input() @HostListener('window:resize', ['$event'])
hotZoneImgSize = 190; onResize(event) {
this.g_winResizeEventStream.next();
}
saveDisabled = true; g_winResizeEventStream = new Subject();
firstTouch = true;
canvasWidth = 1280; canvasWidth = 1280;
canvasHeight = 720; canvasHeight = 720;
canvasBaseW = 1280; canvasBaseW = 1280;
// @HostListener('window:resize', ['$event'])
canvasBaseH = 720; canvasBaseH = 720;
mapScale = 1; mapScale = 1;
currentSelected = null
ctx; ctx;
mx; mx;
my; // 点击坐标 my; // 点击坐标
// 声音
bgAudio = new Audio();
images = new Map();
animationId: any;
// 资源 // 资源
// rawImages = new Map(res); // rawImages = new Map(res);
winResizeEventStream = new Subject();
// 声音
bgAudio = new Audio();
images = new Map();
animationId: any;
// winResizeEventStream = new Subject();
canvasLeft; canvasLeft;
canvasTop; canvasTop;
renderArr; renderArr;
imgArr = []; imgArr = [];
oldPos; oldPos;
radioValue;
curItem; curItem;
bg: MySprite; bg: MySprite;
changeSizeFlag = false; changeSizeFlag = false;
changeTopSizeFlag = false; changeTopSizeFlag = false;
changeRightSizeFlag = false; changeRightSizeFlag = false;
hotZoneChanged = false;
showModalWindow = false;
currentPasteItem = null
copyData = ""
pasteData = ""
scale = 1;
constructor() {
}
_bgItem = null;
get bgItem() {
return this._bgItem;
}
@Input()
set bgItem(v) {
this._bgItem = v;
this.init(); constructor( private nzMessageService: NzMessageService, private el: ElementRef) {
}
onResize(event) {
this.winResizeEventStream.next();
} }
ngOnInit() { ngOnInit() {
if(!this.bgItem.url){
this.bgItem.url = "assets/play/hot-zoo-bg.png"
}
this.initListener(); this.initListener();
// this.init();
this.update(); this.update();
} }
ngOnDestroy() { ngOnDestroy() {
window.cancelAnimationFrame(this.animationId); window.cancelAnimationFrame(this.animationId);
} }
ngOnChanges() { ngOnChanges() {
} }
onBackgroundUploadSuccess(e) { onBackgroundUploadSuccess(e) {
console.log('e: ', e);
this.bgItem.url = e.url; this.bgItem.url = e.url;
this.refreshBackground(); this.refreshBackground(() => {
} this.autoSave()
});
onItemImgUploadSuccess(e, item) {
item.pic_url = e.url;
this.loadHotZonePic(item.pic, e.url);
}
onItemAudioUploadSuccess(e, item) {
item.audio_url = e.url;
} }
refreshBackground(callBack = null) { refreshBackground(callBack = null) {
if (!this.bg) { if (!this.bg) {
this.bg = new MySprite(this.ctx); this.bg = new MySprite(this.ctx);
this.renderArr.push(this.bg); this.renderArr.push(this.bg);
} }
const bg = this.bg; const bg = this.bg;
if (this.bgItem.url) { bg.load("assets/play/hot-zoo-bg.png").then(() => {
const rate1 = this.canvasWidth / bg.width;
bg.load(this.bgItem.url).then(() => { const rate2 = this.canvasHeight / bg.height;
const rate1 = this.canvasWidth / bg.width; const rate = Math.min(rate1, rate2);
const rate2 = this.canvasHeight / bg.height; bg.setScaleXY(rate);
bg.x = this.canvasWidth / 2;
const rate = Math.min(rate1, rate2); bg.y = this.canvasHeight / 2;
bg.setScaleXY(rate); if (callBack) {
callBack();
}
bg.x = this.canvasWidth / 2; }).catch((error) => {
bg.y = this.canvasHeight / 2; console.log(error)
})
if (callBack) {
callBack();
}
});
}
} }
addBtnClick(array) {
addBtnClick() { const item = this.getHotZoneItem(null, null, true);
// this.imgArr.push({}); item.type = "Image"
// this.hotZoneArr.push({}); array.push(item);
const item = this.getHotZoneItem();
this.hotZoneArr.push(item);
this.refreshItem(item);
this.refreshHotZoneId(); this.refreshHotZoneId();
this.autoSave()
}
deleteItem(array, i) {
array.splice(i, 1);
this.refreshHotZoneId();
this.autoSave()
} }
deleteBtnClick(index) { handleMoveItemUp(items, index) {
if (index != 0) {
items[index] =items.splice(index - 1, 1,items[index])[0];
} else {
items.push(this.hotZoneArr.shift());
}
this.autoSave()
}
const item = this.hotZoneArr.splice(index, 1)[0]; handleMoveItemDown(items, index) {
removeItemFromArr(this.renderArr, item.pic); if (index != items.length - 1) {
removeItemFromArr(this.renderArr, item.textLabel); items[index] = items.splice(index + 1, 1, items[index])[0];
} else {
items.unshift(items.splice(index, 1)[0]);
}
this.autoSave()
}
this.refreshHotZoneId(); onImgUploadSuccessByImg(e, item) {
item.pic_url = e.url;
item.image_url = e.url;
item.initNew((w, h) => {
item.setScaleXY(Math.min(100 / w, 150 / h))
})
this.refreshImage(item);
this.autoSave()
}
onUploadSuccessByItem(e, items, key, type){
items[key] = e.url;
let textSaved = items.text
if(type == "image"){
items.initNew((w, h) => {
items.text = textSaved
items.setScaleXY(Math.min(100 / w, 150 / h))
})
this.refreshImage(items)
}
this.autoSave()
}
showPasteModal(it): void {
this.currentPasteItem = it
this.showModalWindow = true;
setTimeout(() => {
this.pasteDataContainer.nativeElement.focus();
}, 10);
}
handlePasteOk(){
if(this.pasteData && this.currentPasteItem){
let pos = this.pasteData.split(";")
if(pos.length == 5){
let result = true;
let reg = /^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$/
pos.forEach(item=>{
if(!reg.test(item)){
result = false;
}
})
if(result){
this.currentPasteItem.x = Number(pos[0])
this.currentPasteItem.y = Number(pos[1])
this.currentPasteItem.width = Number(pos[2]) / this.currentPasteItem.scaleX
this.currentPasteItem.height = Number(pos[3]) / this.currentPasteItem.scaleY
this.currentPasteItem.rotation = Number(pos[4])
this.autoSave()
this.init()
}
}
}
this.pasteData = ""
this.currentPasteItem = null
this.showModalWindow = false;
}
handlePasteCancle(){
this.pasteData = ""
this.currentPasteItem = null
this.showModalWindow = false;
} }
onImgUploadSuccessByImg(e, img) { copyPositionData(item){
img.pic_url = e.url; this.nzMessageService.info('Copied');
this.refreshImage(img); document.addEventListener('copy', handleData);
document.execCommand('copy');
document.removeEventListener('copy', handleData);
function handleData(e) {
let bb = item.getBoundingBox()
e.clipboardData.setData('text/plain', `${Math.round(item.x*100)/100};${Math.round(item.y*100)/100};${Math.round(bb.width*100)/100};${Math.round(bb.height*100)/100};${Math.round(item.rotation*100)/100}`);
e.preventDefault();
}
} }
refreshImage(img) { refreshImage(img) {
this.hideAllLineDash(); this.hideAllLineDash();
img.picItem = this.getPicItem(img); img.picItem = this.getPicItem(img);
this.refreshImageId(); this.refreshImageId();
} }
refreshHotZoneId() { refreshHotZoneId() {
for (let i = 0; i < this.hotZoneArr.length; i++) { for (let i = 0; i < this.hotZoneArr.length; i++) {
this.hotZoneArr[i].index = i; this.hotZoneArr[i].index = i;
if (this.hotZoneArr[i]) {
this.hotZoneArr[i].title = 'item-' + (i + 1);
}
} }
} }
refreshHotZoneText(item) {
item.initNew()
}
refreshImageId() { refreshImageId() {
for (let i = 0; i < this.imgArr.length; i++) { for (let i = 0; i < this.imgArr.length; i++) {
this.imgArr[i].id = i; this.imgArr[i].id = i;
if (this.imgArr[i].picItem) { if (this.imgArr[i].picItem) {
this.imgArr[i].picItem.text = 'Image-' + (i + 1); this.imgArr[i].picItem.text = 'Image-' + (i + 1);
} }
} }
} }
getHotZoneItem(saveData = null) { getHotZoneItem(saveData = null, newRect?, offSetCenter=false) {
const itemW = 200; const itemW = 200;
const itemH = 200; const itemH = 200;
const item = new HotZoneItem(this.ctx); const item = new HotZoneImageItem(this.ctx);
item.setSize(itemW, itemH); item.offSetCenter = offSetCenter
item.anchorX = 0.5;
item.anchorY = 0.5;
item.x = this.canvasWidth / 2;
item.y = this.canvasHeight / 2;
item.itemType = this.defaultItemType;
if (saveData) { if (saveData) {
item.init(saveData.media.image_url, saveData.media.text, saveData.media.type, (w, h) => {
const saveRect = saveData.rect; const saveRect = saveData.rect;
item.scaleX = saveRect.width / item.width; item.scaleX = (saveData.rect.width / saveData.scale) / w;
item.scaleY = saveRect.height / item.height; item.scaleY = (saveData.rect.height / saveData.scale) / h;
item.x = saveRect.x + saveRect.width / 2; if(item.offSetCenter){
item.y = saveRect.y + saveRect.height / 2; item.x = (saveRect.x + saveRect.width/2) / saveData.scale + newRect.x
item.y = (saveRect.y + saveRect.height/2) / saveData.scale + newRect.y
} }else{
item.x = saveRect.x / saveData.scale + newRect.x
item.showLineDash(); item.y = saveRect.y / saveData.scale + newRect.y
}
const pic = new HotZoneImg(this.ctx); });
pic.visible = false; item.rotation = saveData.rect.rotation
item['pic'] = pic; item.image_url = saveData.media.image_url
if (saveData && saveData.pic_url) { item.attImage_url = saveData.media.attImage_url
this.loadHotZonePic(pic, saveData.pic_url); item.audio_url = saveData.media.audio_url
} item.text = saveData.media.text
pic.x = item.x; item.type = saveData.media.type
pic.y = item.y;
this.renderArr.push(pic); } else {
item.init("assets/play/bg_sentence.png", null, "Image", () => {
const textLabel = new HotZoneLabel(this.ctx); item.image_url = "assets/play/bg_sentence.png"
textLabel.fontSize = this.hotZoneFontObj.size; item.x = this.canvasWidth / 2 - 142;
textLabel.fontName = this.hotZoneFontObj.name; item.y = this.canvasHeight / 2 - 15;
textLabel.fontColor = this.hotZoneFontObj.color; }, () => this.autoSave());
textLabel.textAlign = 'center';
// textLabel.setOutline();
// console.log('saveData:', saveData);
item['textLabel'] = textLabel;
textLabel.setScaleXY(this.mapScale);
if (saveData && saveData.text) {
textLabel.text = saveData.text;
textLabel.refreshSize();
} }
textLabel.x = item.x; item.anchorX = 0.5;
textLabel.y = item.y; item.anchorY = 0.5;
this.renderArr.push(textLabel);
return item; return item;
} }
getPicItem(img, saveData = null) { getPicItem(img, saveData = null) {
const item = new EditorItem(this.ctx); const item = new EditorItem(this.ctx);
item.load(img.pic_url).then(img => { item.load(img.image_url).then(img => {
let maxW, maxH; let maxW, maxH;
if (this.bg) { if (this.bg) {
maxW = this.bg.width * this.bg.scaleX; maxW = this.bg.width * this.bg.scaleX;
...@@ -307,10 +319,8 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -307,10 +319,8 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
maxW = this.canvasWidth; maxW = this.canvasWidth;
maxH = this.canvasHeight; maxH = this.canvasHeight;
} }
let scaleX = maxW / 3 / item.width; let scaleX = maxW / 3 / item.width;
let scaleY = maxH / 3 / item.height; let scaleY = maxH / 3 / item.height;
if (item.height * scaleX < this.canvasHeight) { if (item.height * scaleX < this.canvasHeight) {
item.setScaleXY(scaleX); item.setScaleXY(scaleX);
} else { } else {
...@@ -318,159 +328,84 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -318,159 +328,84 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
} }
item.x = this.canvasWidth / 2; item.x = this.canvasWidth / 2;
item.y = this.canvasHeight / 2; item.y = this.canvasHeight / 2;
if (saveData) { if (saveData) {
const saveRect = saveData.rect; const saveRect = saveData.rect;
item.setScaleXY(saveRect.width / item.width); item.setScaleXY(saveRect.width / item.width);
item.x = saveRect.x + saveRect.width / 2; item.x = saveRect.x + saveRect.width / 2;
item.y = saveRect.y + saveRect.height / 2; item.y = saveRect.y + saveRect.height / 2;
} else { } else {
item.showLineDash(); item.showLineDash();
} }
this.autoSave()
}); })
return item; return item;
} }
onAudioUploadSuccessByImg(e, img) {
img.audio_url = e.url;
}
deleteItem(e, i) {
// this.imgArr.splice(i , 1);
// this.refreshImageId();
this.hotZoneArr.splice(i, 1);
this.refreshHotZoneId();
}
radioChange(e, item) {
item.itemType = e;
this.refreshItem(item);
// console.log(' in radioChange e: ', e);
}
refreshItem(item) {
switch (item.itemType) {
case 'rect':
this.setRectState(item);
break;
case 'pic':
this.setPicState(item);
break;
case 'text':
this.setTextState(item);
break;
default:
}
}
init() { init() {
this.initData(); this.initData();
this.initCtx(); this.initCtx();
this.initItem(); this.initItem();
} }
initItem() { initItem() {
if (!this.bgItem) { if (!this.bgItem) {
this.bgItem = {}; this.bgItem = {
title: {
mainText: "Read then write a rhyme.",
mainTitleAudio: "",
boardTitle: "Make rhymes",
boardTitleAudio: "",
mainAudio: "",
leftText: "Rhyme 2",
rightText: "Rhyme 1",
leftAudio: "",
rightAudio: ""
}
};
} else { } else {
this.refreshBackground(() => { this.refreshBackground(() => {
// if (!this.imgItemArr) {
// this.imgItemArr = [];
// } else {
// this.initImgArr();
// }
// console.log('aaaaa');
if (!this.hotZoneItemArr) { if (!this.hotZoneItemArr) {
this.hotZoneItemArr = []; this.hotZoneItemArr = [];
} else { } else {
this.initHotZoneArr(); this.initHotZoneArr();
} }
}); });
} }
} }
initHotZoneArr() { initHotZoneArr() {
// console.log('this.hotZoneArr: ', this.hotZoneArr);
let curBgRect; let curBgRect;
if (this.bg) { if (this.bg) {
curBgRect = this.bg.getBoundingBox(); curBgRect = this.bg.getBoundingBox();
} else { } else {
curBgRect = {x: 0, y: 0, width: this.canvasWidth, height: this.canvasHeight}; curBgRect = { x: 0, y: 0, width: this.canvasWidth, height: this.canvasHeight };
} }
let oldBgRect = this.bgItem.rect; let oldBgRect = this.bgItem.rect;
if (!oldBgRect) { if (!oldBgRect) {
oldBgRect = curBgRect; oldBgRect = curBgRect;
} }
const rate = curBgRect.width / oldBgRect.width; const rate = curBgRect.width / oldBgRect.width;
console.log('rate: ', rate);
this.hotZoneArr = [];
const arr = this.hotZoneItemArr.concat(); const arr = this.hotZoneItemArr.concat();
for (let i = 0; i < arr.length; i++) { for (let i = 0; i < arr.length; i++) {
const data = JSON.parse(JSON.stringify(arr[i])); const data = JSON.parse(JSON.stringify(arr[i]));
// const img = {pic_url: data.pic_url};
data.rect.x *= rate; data.rect.x *= rate;
data.rect.y *= rate; data.rect.y *= rate;
data.rect.width *= rate; data.rect.width *= rate;
data.rect.height *= rate; data.rect.height *= rate;
const item = this.getHotZoneItem(data, { x: curBgRect.x, y: curBgRect.y }, true);
data.rect.x += curBgRect.x;
data.rect.y += curBgRect.y;
// img['picItem'] = this.getPicItem(img, data);
// img['audio_url'] = arr[i].audio_url;
// this.imgArr.push(img);
const item = this.getHotZoneItem(data);
item.audio_url = data.audio_url;
item.pic_url = data.pic_url;
item.text = data.text;
item.itemType = data.itemType;
this.refreshItem(item);
console.log('item: ', item);
this.hotZoneArr.push(item); this.hotZoneArr.push(item);
} }
this.refreshHotZoneId(); this.refreshHotZoneId();
// this.refreshImageId();
} }
initImgArr() { initImgArr() {
console.log('this.imgItemArr: ', this.imgItemArr);
let curBgRect; let curBgRect;
if (this.bg) { if (this.bg) {
curBgRect = this.bg.getBoundingBox(); curBgRect = this.bg.getBoundingBox();
} else { } else {
curBgRect = {x: 0, y: 0, width: this.canvasWidth, height: this.canvasHeight}; curBgRect = { x: 0, y: 0, width: this.canvasWidth, height: this.canvasHeight };
} }
let oldBgRect = this.bgItem.rect; let oldBgRect = this.bgItem.rect;
...@@ -479,15 +414,12 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -479,15 +414,12 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
} }
const rate = curBgRect.width / oldBgRect.width; const rate = curBgRect.width / oldBgRect.width;
console.log('rate: ', rate);
this.imgArr = []; this.imgArr = [];
const arr = this.imgItemArr.concat(); const arr = this.imgItemArr.concat();
for (let i = 0; i < arr.length; i++) { for (let i = 0; i < arr.length; i++) {
const data = JSON.parse(JSON.stringify(arr[i])); const data = JSON.parse(JSON.stringify(arr[i]));
const img = {pic_url: data.pic_url}; const img = { pic_url: data.pic_url };
data.rect.x *= rate; data.rect.x *= rate;
data.rect.y *= rate; data.rect.y *= rate;
...@@ -506,13 +438,12 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -506,13 +438,12 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
initData() { initData() {
this.canvasWidth = this.wrap.nativeElement.clientWidth; this.canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight; this.canvasHeight = this.wrap.nativeElement.clientWidth * (555 / 1070);
this.scale = 1070 / this.wrap.nativeElement.clientWidth
this.mapScale = this.canvasWidth / this.canvasBaseW; this.mapScale = this.canvasWidth / this.canvasBaseW;
this.renderArr = []; this.renderArr = [];
this.bg = null; this.bg = null;
this.imgArr = []; this.imgArr = [];
this.hotZoneArr = []; this.hotZoneArr = [];
} }
...@@ -522,46 +453,42 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -522,46 +453,42 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
this.canvas.nativeElement.width = this.canvasWidth; this.canvas.nativeElement.width = this.canvasWidth;
this.canvas.nativeElement.height = this.canvasHeight; this.canvas.nativeElement.height = this.canvasHeight;
} }
mapDown(event) { mapDown(event) {
this.oldPos = { x: this.mx, y: this.my };
const arr = this.hotZoneArr.concat();
for (let i = arr.length - 1; i >= 0; i--) {
const item = arr[i];
if (item) {
if (this.checkClickTarget(item)) {
if (item.lineDashFlag && this.checkClickTarget(item.arrow)) {
if(item.type == "Text"){
return
}
this.changeItemSize(item);
} else if (item.lineDashFlag && this.checkClickTarget(item.arrowTop)) {
if(item.type == "Text"){
return
}
this.changeItemTopSize(item);
} else if (item.lineDashFlag && this.checkClickTarget(item.arrowRight)) {
if(item.type == "Text"){
return
}
this.changeItemRightSize(item);
} else {
this.changeCurItem(item);
}
this.hotZoneChanged = true;
return;
}
this.oldPos = {x: this.mx, y: this.my};
for (let i = 0; i < this.hotZoneArr.length; i++) {
const item = this.hotZoneArr[i];
let callback;
let target;
switch (item.itemType) {
case 'rect':
target = item;
callback = this.clickedHotZoneRect.bind(this);
break;
case 'pic':
target = item.pic;
callback = this.clickedHotZonePic.bind(this);
break;
case 'text':
target = item.textLabel;
callback = this.clickedHotZoneText.bind(this);
break;
}
if (this.checkClickTarget(target)) {
callback(target);
return;
} }
} }
} }
mapMove(event) { mapMove(event) {
if (!this.curItem) { if (!this.curItem) { return; }
return;
}
if (this.changeSizeFlag) { if (this.changeSizeFlag) {
this.changeSize(); this.changeSize();
...@@ -571,19 +498,14 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -571,19 +498,14 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
} else if (this.changeRightSizeFlag) { } else if (this.changeRightSizeFlag) {
this.changeRightSize(); this.changeRightSize();
} else { } else {
let addX = this.mx - this.oldPos.x;
const addX = this.mx - this.oldPos.x; let addY = this.my - this.oldPos.y;
const addY = this.my - this.oldPos.y;
this.curItem.x += addX; this.curItem.x += addX;
this.curItem.y += addY; this.curItem.y += addY;
} }
this.oldPos = {x: this.mx, y: this.my}; this.oldPos = { x: this.mx, y: this.my };
this.saveDisabled = true;
} }
mapUp(event) { mapUp(event) {
...@@ -593,79 +515,68 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -593,79 +515,68 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
this.changeRightSizeFlag = false; this.changeRightSizeFlag = false;
} }
changeSize() { changeSize() {
const rect = this.curItem.getBoundingBox(); const rect = this.curItem.getBoundingBox();
let distance = null;
let lenW = (this.mx - (rect.x + rect.width / 2)) * 2; let lenW = null;
let lenH = ((rect.y + rect.height / 2) - this.my) * 2; if(this.curItem.offSetCenter){
distance = (this.my + rect.height/2) - rect.y
lenW = (this.mx + rect.width/2) - rect.x;
}else{
distance = this.my - rect.y;
lenW = this.mx - rect.x;
}
let lenH = rect.height - distance
let minLen = 20; let minLen = 20;
let s; let sx, sy;
if (lenW < lenH) { if (lenW < minLen) {
if (lenW < minLen) { lenW = minLen;
lenW = minLen;
}
s = lenW / this.curItem.width;
} else {
if (lenH < minLen) {
lenH = minLen;
}
s = lenH / this.curItem.height;
} }
sx = lenW / this.curItem.width;
if (lenH < minLen) {
// console.log('s: ', s); lenH = minLen;
this.curItem.setScaleXY(s); }
this.curItem.refreshLabelScale(); sy = lenH / this.curItem.height;
this.curItem.y = this.curItem.y + distance
this.curItem.scaleX = sx;
this.curItem.scaleY = sy;
} }
changeTopSize() { changeTopSize() {
const rect = this.curItem.getBoundingBox(); const rect = this.curItem.getBoundingBox();
let lenH = null
// let lenW = ( this.mx - (rect.x + rect.width / 2) ) * 2; if(this.curItem.offSetCenter){
let lenH = ((rect.y + rect.height / 2) - this.my) * 2; lenH = rect.y - (this.my + rect.height/2) + rect.height;
this.curItem.y = this.my + rect.height/2
}else{
lenH = rect.y - this.my + rect.height;
this.curItem.y = this.my
}
let minLen = 20; let minLen = 20;
let s; let s;
// if (lenW < lenH) {
// if (lenW < minLen) {
// lenW = minLen;
// }
// s = lenW / this.curItem.width;
//
// } else {
if (lenH < minLen) { if (lenH < minLen) {
lenH = minLen; lenH = minLen;
} }
s = lenH / this.curItem.height; s = lenH / this.curItem.height;
// } this.curItem.setScaleXY(s);
// console.log('s: ', s);
this.curItem.scaleY = s;
this.curItem.refreshLabelScale();
} }
changeRightSize() { changeRightSize() {
const rect = this.curItem.getBoundingBox(); const rect = this.curItem.getBoundingBox();
let lenW = null
let lenW = (this.mx - (rect.x + rect.width / 2)) * 2; if(this.curItem.offSetCenter){
// let lenH = ( (rect.y + rect.height / 2) - this.my ) * 2; lenW = this.mx - rect.x + rect.width/2;
}else{
lenW = this.mx - rect.x;
}
let minLen = 20; let minLen = 20;
let s; let s;
if (lenW < minLen) { if (lenW < minLen) {
lenW = minLen; lenW = minLen;
} }
s = lenW / this.curItem.width; s = lenW / this.curItem.width;
this.curItem.setScaleXY(s);
this.curItem.scaleX = s;
this.curItem.refreshLabelScale();
} }
changeItemSize(item) { changeItemSize(item) {
...@@ -692,7 +603,6 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -692,7 +603,6 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
} }
hideAllLineDash() { hideAllLineDash() {
for (let i = 0; i < this.imgArr.length; i++) { for (let i = 0; i < this.imgArr.length; i++) {
if (this.imgArr[i].picItem) { if (this.imgArr[i].picItem) {
this.imgArr[i].picItem.hideLineDash(); this.imgArr[i].picItem.hideLineDash();
...@@ -700,32 +610,14 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -700,32 +610,14 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
} }
} }
update() { update() {
if (!this.ctx) {
return;
}
this.animationId = window.requestAnimationFrame(this.update.bind(this)); this.animationId = window.requestAnimationFrame(this.update.bind(this));
// 清除画布内容 // 清除画布内容
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
for (let i = 0; i < this.renderArr.length; i++) { for (let i = 0; i < this.renderArr.length; i++) {
this.renderArr[i].update(this); this.renderArr[i].update(this);
} }
// for (let i = 0; i < this.imgArr.length; i++) {
// const picItem = this.imgArr[i].picItem;
// if (picItem) {
// picItem.update(this);
// }
// }
this.updateArr(this.hotZoneArr); this.updateArr(this.hotZoneArr);
this.updatePos()
TWEEN.update(); TWEEN.update();
} }
...@@ -737,7 +629,6 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -737,7 +629,6 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
} }
} }
renderAfterResize() { renderAfterResize() {
this.canvasWidth = this.wrap.nativeElement.clientWidth; this.canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight; this.canvasHeight = this.wrap.nativeElement.clientHeight;
...@@ -745,79 +636,94 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -745,79 +636,94 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
} }
initListener() { initListener() {
const element = this.canvas.nativeElement;
this.g_winResizeEventStream.pipe(debounceTime(500)).subscribe(data => {
this.renderAfterResize();
});
const addTouchListener = () => {
element.addEventListener('touchstart', touchDownFunc);
element.addEventListener('touchmove', touchMoveFunc);
element.addEventListener('touchend', touchUpFunc);
element.addEventListener('touchcancel', touchUpFunc);
};
const removeTouchListener = () => {
element.removeEventListener('touchstart', touchDownFunc);
element.removeEventListener('touchmove', touchMoveFunc);
element.removeEventListener('touchend', touchUpFunc);
element.removeEventListener('touchcancel', touchUpFunc);
};
const addMouseListener = () => {
element.addEventListener('mousedown', mouseDownFunc);
element.addEventListener('mousemove', mouseMoveFunc);
element.addEventListener('mouseup', mouseUpFunc);
};
const removeMouseListener = () => {
element.removeEventListener('mousedown', mouseDownFunc);
element.removeEventListener('mousemove', mouseMoveFunc);
element.removeEventListener('mouseup', mouseUpFunc);
};
const touchDownFunc = (e) => {
if (this.firstTouch) {
this.firstTouch = false;
removeMouseListener();
}
setMxMyByTouch(e);
this.mapDown(e);
};
const touchMoveFunc = (e) => {
setMxMyByTouch(e);
this.mapMove(e);
};
const touchUpFunc = (e) => {
setMxMyByTouch(e);
this.mapUp(e);
};
const mouseDownFunc = (e) => {
if (this.firstTouch) {
this.firstTouch = false;
removeTouchListener();
}
setMxMyByMouse(e);
this.mapDown(e);
};
const mouseMoveFunc = (e) => {
setMxMyByMouse(e);
this.mapMove(e);
};
const mouseUpFunc = (e) => {
setMxMyByMouse(e);
this.mapUp(e);
};
const setMxMyByTouch = event => {
if (event.touches.length <= 0) {
return;
}
if (this.canvasLeft == null) {
setParentOffset();
}
this.mx = event.touches[0].pageX - this.canvasLeft;
this.my = event.touches[0].pageY - this.canvasTop;
};
this.winResizeEventStream const setParentOffset = () => {
.pipe(debounceTime(500)) const rect = this.canvas.nativeElement.getBoundingClientRect();
.subscribe(data => { this.canvasLeft = rect.left;
this.renderAfterResize(); this.canvasTop = rect.top;
}); };
if (this.IsPC()) {
this.canvas.nativeElement.addEventListener('mousedown', (event) => {
setMxMyByMouse(event);
this.mapDown(event);
});
this.canvas.nativeElement.addEventListener('mousemove', (event) => {
setMxMyByMouse(event);
this.mapMove(event);
});
this.canvas.nativeElement.addEventListener('mouseup', (event) => {
setMxMyByMouse(event);
this.mapUp(event);
});
const setMxMyByMouse = (event) => {
this.mx = event.offsetX;
this.my = event.offsetY;
};
} else {
this.canvas.nativeElement.addEventListener('touchstart', (event) => {
setMxMyByTouch(event);
this.mapDown(event);
});
this.canvas.nativeElement.addEventListener('touchmove', (event) => {
setMxMyByTouch(event);
this.mapMove(event);
});
this.canvas.nativeElement.addEventListener('touchend', (event) => {
setMxMyByTouch(event);
this.mapUp(event);
});
this.canvas.nativeElement.addEventListener('touchcancel', (event) => {
setMxMyByTouch(event);
this.mapUp(event);
});
const setMxMyByTouch = (event) => {
if (event.touches.length <= 0) {
return;
}
if (this.canvasLeft == null) {
setParentOffset();
}
this.mx = event.touches[0].pageX - this.canvasLeft;
this.my = event.touches[0].pageY - this.canvasTop;
};
const setMxMyByMouse = (event) => {
this.mx = event.offsetX;
this.my = event.offsetY;
};
const setParentOffset = () => { addMouseListener();
addTouchListener();
const rect = this.canvas.nativeElement.getBoundingClientRect();
this.canvasLeft = rect.left;
this.canvasTop = rect.top;
};
}
} }
IsPC() { IsPC() {
...@@ -833,10 +739,15 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -833,10 +739,15 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
checkClickTarget(target) { checkClickTarget(target) {
const rect = target.getBoundingBox(); const rect = target.getBoundingBox();
if (this.checkPointInRect(this.mx, this.my, rect)) { if(target.offSetCenter){
return true; if (this.checkPointInRectOffSetCenter(this.mx, this.my, rect)) {
return true;
}
}else{
if (this.checkPointInRect(this.mx, this.my, rect)) {
return true;
}
} }
return false; return false;
} }
...@@ -850,137 +761,60 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges { ...@@ -850,137 +761,60 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
return false; return false;
} }
checkPointInRectOffSetCenter(x, y, rect) {
if (x >= rect.x - rect.width/2 && x <= rect.x + rect.width/2) {
if (y >= rect.y - rect.height/2 && y <= rect.y + rect.height/2) {
return true;
}
}
return false;
}
saveClick() { autoSave() {
// console.log("Auto save")
const bgItem = this.bgItem; const bgItem = this.bgItem;
if (this.bg) { if (this.bg) {
bgItem['rect'] = this.bg.getBoundingBox(); bgItem['rect'] = this.bg.getBoundingBox();
} else { } else {
bgItem['rect'] = { bgItem['rect'] = { x: 0, y: 0, width: Math.round(this.canvasWidth * 100) / 100, height: Math.round(this.canvasHeight * 100) / 100 };
x: 0,
y: 0,
width: Math.round(this.canvasWidth * 100) / 100,
height: Math.round(this.canvasHeight * 100) / 100
};
} }
const hotZoneItemArr = []; const hotZoneItemArr = [];
const hotZoneArr = this.hotZoneArr; const hotZoneArr = this.hotZoneArr;
for (let i = 0; i < hotZoneArr.length; i++) { for (let i = 0; i < hotZoneArr.length; i++) {
const hotZoneItem = { const hotZoneItem = {
index: hotZoneArr[i].index, index: hotZoneArr[i].index,
pic_url: hotZoneArr[i].pic_url,
text: hotZoneArr[i].text,
audio_url: hotZoneArr[i].audio_url,
itemType: hotZoneArr[i].itemType,
fontSize: this.hotZoneFontObj.size,
fontName: this.hotZoneFontObj.name,
fontColor: this.hotZoneFontObj.color,
fontScale: hotZoneArr[i].textLabel ? hotZoneArr[i].textLabel.scaleX : 1,
imgScale: hotZoneArr[i].pic ? hotZoneArr[i].pic.scaleX : 1,
mapScale: this.mapScale
}; };
hotZoneItem['rect'] = hotZoneArr[i].getBoundingBox(); hotZoneItem['rect'] = hotZoneArr[i].getBoundingBox();
hotZoneItem['rect'].x = Math.round((hotZoneItem['rect'].x - bgItem['rect'].x) * 100) / 100; const currentX = hotZoneItem['rect'].x
hotZoneItem['rect'].y = Math.round((hotZoneItem['rect'].y - bgItem['rect'].y) * 100) / 100; const currentY = hotZoneItem['rect'].y
hotZoneItem['rect'].width = Math.round((hotZoneItem['rect'].width) * 100) / 100; hotZoneItem['media'] = {}
hotZoneItem['rect'].height = Math.round((hotZoneItem['rect'].height) * 100) / 100; hotZoneItem['scale'] = this.scale
if(hotZoneArr[i].offSetCenter){
hotZoneItem['rect'].x = (Math.round((currentX - bgItem['rect'].x - hotZoneItem['rect'].width / 2) * 100) / 100) * this.scale;
hotZoneItemArr.push(hotZoneItem); hotZoneItem['rect'].y = (Math.round((currentY - bgItem['rect'].y - hotZoneItem['rect'].height /2) * 100) / 100) * this.scale;
} }else{
hotZoneItem['rect'].x = (Math.round((currentX - bgItem['rect'].x) * 100) / 100) * this.scale;
console.log('hotZoneItemArr: ', hotZoneItemArr); hotZoneItem['rect'].y = (Math.round((currentY - bgItem['rect'].y) * 100) / 100) * this.scale;
this.save.emit({bgItem, hotZoneItemArr});
}
private updatePos() {
this.hotZoneArr.forEach((item) => {
let x, y;
switch (item.itemType) {
case 'rect':
x = item.x;
y = item.y;
break;
case 'pic':
x = item.pic.x;
y = item.pic.y;
break;
case 'text':
x = item.textLabel.x;
y = item.textLabel.y;
break;
}
item.x = x;
item.y = y;
item.pic.x = x;
item.pic.y = y;
item.textLabel.x = x;
item.textLabel.y = y;
});
}
private setPicState(item: any) {
item.visible = false;
item.textLabel.visible = false;
item.pic.visible = true;
}
private setRectState(item: any) {
item.visible = true;
item.textLabel.visible = false;
item.pic.visible = false;
}
private setTextState(item: any) {
item.visible = false;
item.pic.visible = false;
item.textLabel.visible = true;
}
private clickedHotZoneRect(item: any) {
if (this.checkClickTarget(item)) {
if (item.lineDashFlag && this.checkClickTarget(item.arrow)) {
this.changeItemSize(item);
} else if (item.lineDashFlag && this.checkClickTarget(item.arrowTop)) {
this.changeItemTopSize(item);
} else if (item.lineDashFlag && this.checkClickTarget(item.arrowRight)) {
this.changeItemRightSize(item);
} else {
this.changeCurItem(item);
} }
return; hotZoneItem['rect'].width = (Math.round((hotZoneItem['rect'].width) * 100) / 100) * this.scale;
} hotZoneItem['rect'].height = (Math.round((hotZoneItem['rect'].height) * 100) / 100) * this.scale;
} hotZoneItem['rect'].rotation = hotZoneArr[i].rotation
hotZoneItem['media'].image_url = hotZoneArr[i].image_url
private clickedHotZonePic(item: any) { hotZoneItem['media'].attImage_url = hotZoneArr[i].attImage_url
if (this.checkClickTarget(item)) { hotZoneItem['media'].audio_url = hotZoneArr[i].audio_url
this.curItem = item; hotZoneItem['media'].text = hotZoneArr[i].text
} hotZoneItem['media'].type = hotZoneArr[i].type
} hotZoneItemArr.push(hotZoneItem);
private clickedHotZoneText(item: any) {
if (this.checkClickTarget(item)) {
this.curItem = item;
} }
}
saveText(item) { this.save.emit({ bgItem, hotZoneItemArr });
item.textLabel.text = item.text; this.hotZoneChanged = false;
} }
private loadHotZonePic(pic: HotZoneImg, url) { saveClick() {
const baseLen = this.hotZoneImgSize * this.mapScale; // console.log("Saved")
pic.load(url).then(() => { this.autoSave()
const s = getMinScale(pic, baseLen);
pic.setScaleXY(s);
});
} }
} }
<div class="title-config"> <div class="title-config">
<div class="title-wrap"> <div class="title-wrap">
<div class="row" style="margin: 5px;"> <div class="row" style="margin: 5px;">
<div class="p-content" style="width:100%"> <div class="p-content" style="width:100%">
<div class="p-tool-box d-flex" style="background: #fff;"> <div class="p-tool-box d-flex" style="background: #fff;">
<nz-select class="ml-1" style="width: 120px;" [(ngModel)]="__fontFamily" <nz-select class="ml-1" style="width: 120px;" [(ngModel)]="__fontFamily"
(ngModelChange)="onChangeFontFamily($event)" (ngModelChange)="onChangeFontFamily($event)"
nzPlaceHolder="Font Family" nzPlaceHolder="Font Family"
[nzDropdownMatchSelectWidth]="false"> [nzDropdownMatchSelectWidth]="false"
<nz-option [nzValue]="font" nzCustomContent [nzLabel]="font" *ngFor="let font of fontFamilyList"> >
<span [ngStyle]="{'font-family': font}" >{{font}}</span> <nz-option [nzValue]="font" [nzLabel]="font" *ngFor="let font of fontFamilyList"></nz-option>
</nz-option> </nz-select>
</nz-select>
<nz-select class="ml-1" style="width: 110px;" [(ngModel)]="__fontSize" <nz-select class="ml-1" style="width: 110px;" [(ngModel)]="__fontSize"
(ngModelChange)="onChangeFontSize()" (ngModelChange)="onChangeFontSize()"
nzPlaceHolder="Font Size"> nzPlaceHolder="Font Size">
<nz-option [nzValue]="i" [nzLabel]="'Size - ' + i" *ngFor="let i of fontSizeRange"></nz-option> <nz-option [nzValue]="i" [nzLabel]="'Size - ' + i" *ngFor="let i of fontSizeRange"></nz-option>
</nz-select> </nz-select>
<div class="p-divider"></div> <div class="p-divider"></div>
<div class="i-tool-font-btn d-flex mr-2"> <div class="i-tool-font-btn d-flex mr-2">
<div class="position-relative fa-icon" (click)="onChangeBold()"> <div class="position-relative fa-icon" (click)="onChangeBold()">
<!-- <div class="fa fa-bold"></div>--> <div class="fa fa-bold"></div>
<fa-icon icon="bold"></fa-icon>
</div> </div>
</div> </div>
<div class="i-tool-font-btn d-flex mr-2"> <div class="i-tool-font-btn d-flex mr-2">
<div class="position-relative fa-icon" (click)="onChangeItalic()"> <div class="position-relative fa-icon" (click)="onChangeItalic()">
<!-- <div class="fa fa-italic"></div>--> <div class="fa fa-italic"></div>
<fa-icon icon="italic"></fa-icon>
</div> </div>
</div> </div>
<div class="i-tool-font-btn d-flex mr-2"> <div class="i-tool-font-btn d-flex mr-2">
<div class="position-relative fa-icon" (click)="onChangeUnderline()"> <div class="position-relative fa-icon" (click)="onChangeUnderline()">
<!-- <div class="fa fa-underline"></div>--> <div class="fa fa-underline"></div>
<fa-icon icon="underline"></fa-icon>
</div> </div>
</div> </div>
<div class="i-tool-font-btn d-flex"> <div class="i-tool-font-btn d-flex">
<div class="position-relative fa-icon" (click)="onChangeStrikethrough()"> <div class="position-relative fa-icon" (click)="onChangeStrikethrough()">
<!-- <div class="fa fa-strikethrough"></div>--> <div class="fa fa-strikethrough"></div>
<fa-icon icon="strikethrough"></fa-icon>
</div> </div>
</div> </div>
<div class="p-divider"></div> <div class="p-divider"></div>
<div class="i-tool-font-color d-flex"> <div class="i-tool-font-color d-flex">
<div class="position-relative i-left flex-fill" (click)="onChangeFontColor($event)"> <div class="position-relative i-left flex-fill" (click)="onChangeFontColor($event)">
<!-- <div class="fa fa-font"></div>--> <div class="fa fa-font"></div>
<fa-icon icon="palette"></fa-icon>
<div class="i-color" [style.background-color]="__fontColor"></div> <div class="i-color" [style.background-color]="__fontColor"></div>
</div> </div>
<div class="i-dropdown-menu" nzPlacement="bottom" <div class="i-dropdown-menu" nzPlacement="bottom"
nz-popover [(nzVisible)]="isShowFontColorPane" nzTrigger="click" nz-popover [(nzVisible)]="isShowFontColorPane" nzTrigger="click"
[nzContent]="colorPane"> [nzContent]="colorPane">
<i nz-icon type="down" theme="outline"></i> <i nz-icon type="down" theme="outline"></i>
</div> </div>
</div> </div>
<div class="p-divider"></div> <div class="p-divider"></div>
<div style="background: #fff;display: block;"> <div style="background: #fff;display: block;">
<div class="position-relative"> <div class="position-relative" (click)="onChangeStrikethrough()">
<app-audio-recorder [audioUrl]="titleObj && titleObj.audio_url" (audioUploaded)="titleAudioUploaded($event)"></app-audio-recorder> <app-audio-recorder [audioUrl]="titleObj && titleObj.audio_url" (audioUploaded)="titleAudioUploaded($event)"></app-audio-recorder>
</div> </div>
</div> </div>
</div> </div>
<div class="width-100 d-flex"> <div class="width-100 d-flex">
<iframe #titleEl id="titleContentEgret" frameborder="0" style="overflow: hidden;width: 100%; height:48px; margin: 0; padding: 0;"></iframe> <iframe #titleEl frameborder="0" style="overflow: hidden;width: 100%; height:48px; margin: 0; padding: 0;"></iframe>
</div> </div>
</div> </div>
...@@ -83,11 +76,37 @@ ...@@ -83,11 +76,37 @@
<ng-container *ngIf="withIcon">
<div class="row type-row">
课程类型:
<nz-radio-group [(ngModel)]="titleObj && titleObj.type" (ngModelChange)="typeChange($event)">
<label nz-radio nzValue="a">单数课</label>
<label nz-radio nzValue="b">双数课</label>
<label nz-radio nzValue="c">复习课</label>
</nz-radio-group>
</div>
</ng-container>
</div> </div>
<ng-container *ngIf="withIcon">
<div class="title-icons">
<div class="icons-list">
<nz-checkbox-wrapper style="width: 100%;clear:both" (nzOnChange)="iconsChanges($event)">
<div [class]="'icon-item icon-'+i" *ngFor="let i of groupIconsCount[titleObj.type];">
<div class="img-box">
<nz-badge class="icon-badge" [nzCount]="titleObj && titleObj.icons && titleObj.icons.indexOf(i) + 1">
<img [src]="'assets/title-icons/'+titleObj.type+'/icon-'+i+'.png'" alt="">
</nz-badge>
</div>
<label nz-checkbox [nzValue]="i" [ngModel]="titleObj && titleObj.icons && titleObj.icons.indexOf(i) > -1"></label>
</div>
</nz-checkbox-wrapper>
</div>
</div>
</ng-container>
</div> </div>
@import '../../style/common_mixin.css'; @import '../../style/common_mixin';
.title-config { .title-config {
.letter-wrap{ .letter-wrap{
...@@ -11,73 +11,39 @@ ...@@ -11,73 +11,39 @@
.type-row{ .type-row{
margin: 0;padding-top: 1rem; margin: 0;padding-top: 1rem;
} }
.icon-item{
margin-right: 16px;
float: left;
width: 45px;
height: 75px;
display: flex;
justify-content: center;
align-items: center;
position: relative;
.icon-badge{
position: absolute;
top: 0;
right: 0;
}
.img-box{
top: 0;
position: absolute;
width: 45px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
img{
max-width: 100%;
}
}
label{
position: absolute;
bottom: 0;
}
}
}
}
@font-face
{
font-family: 'BRLNSDB';
src: url("../../../assets/font/BRLNSDB.TTF") ;
}
@font-face
{
font-family: 'BRLNSB';
src: url("../../../assets/font/BRLNSB.TTF") ;
}
@font-face
{
font-family: 'BRLNSR';
src: url("../../../assets/font/BRLNSR.TTF") ;
}
@font-face
{
font-family: 'GOTHIC';
src: url("../../../assets/font/GOTHIC.TTF") ;
}
@font-face
{
font-family: 'GOTHICB';
src: url("../../../assets/font/GOTHICB.TTF") ;
}
@font-face
{
font-family: 'GOTHICBI';
src: url("../../../assets/font/GOTHICBI.TTF") ;
}
@font-face
{
font-family: 'GOTHICI';
src: url("../../../assets/font/GOTHICI.TTF") ;
}
@font-face
{
font-family: 'MMTextBook';
src: url("../../../assets/font/MMTextBook.otf") ;
}
@font-face
{
font-family: 'MMTextBook-Bold';
src: url("../../../assets/font/MMTextBook-Bold.otf") ;
}
@font-face
{
font-family: 'MMTextBook-BoldItalic';
src: url("../../../assets/font/MMTextBook-BoldItalic.otf") ;
}
@font-face
{
font-family: 'MMTextBook-Italic';
src: url("../../../assets/font/MMTextBook-Italic.otf") ;
}
@mixin tool-btn { @mixin tool-btn {
border: 1px solid #ddd; border: 1px solid #ddd;
display: flex; display: flex;
...@@ -88,37 +54,16 @@ ...@@ -88,37 +54,16 @@
border-radius: 6px; border-radius: 6px;
color: #555; color: #555;
} }
.d-flex{
display: flex;
}
.position-relative {
position: relative;
}
.flex-fill {
-webkit-box-flex: 1;
flex: 1 1 auto;
justify-content: center;
display: flex;
}
.i-dropdown-menu{ .p-title-box {
width: 15px; .p-title {
font-size: 10px;
border-left: 1px solid #ddd;
display: -webkit-box;
display: flex;
-webkit-box-align: center;
align-items: center;
flex: 0
}
.p-title-box .p-title {
font-size: 20px; font-size: 20px;
} }
.p-title-box input { input {
width: 300px; width: 300px;
margin-left: 10px; margin-left: 10px;
} }
}
.p-content { .p-content {
border: 1px solid #ddd; border: 1px solid #ddd;
...@@ -140,110 +85,115 @@ ...@@ -140,110 +85,115 @@
align-items: center; align-items: center;
border-bottom: 1px solid #ddd; border-bottom: 1px solid #ddd;
// save
.i-tool-save {
@include tool-btn();
color: white;
}
.i-tool-save:disabled {
color: #555;
}
// font-size
.i-tool-font-size {
@include tool-btn();
width: 37px;
} & > span {
// save
.i-tool-save {
//@include tool-btn();
color: white;
}
.i-tool-save:disabled {
color: #555;
}
// font-size
.i-tool-font-size {
//@include tool-btn();
width: 37px;
}
.i-tool-font-size:hover {
color: black;
border-color: #bbb;
}
// font-color
.i-tool-font-color, .i-tool-font-btn {
border: 1px solid #ddd;
//padding: 3px 7px;
border-radius: 6px;
width: 45px;
height: 31px;
background-color: white;
color: #555;
::ng-deep > span {
display: flex;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
padding: 3px 7px;
}
.i-left {
.fa-font,.fa-bold,.fa-italic,.fa-strikethrough, .fa-underline {
font-size: 10px;
position: absolute; position: absolute;
color: #555; top: -5px;
left: 8px; right: 5px;
top: 7px;
} }
.i-color { }
width: 68%; .i-tool-font-size:hover {
height: 5px; color: black;
background-color: black; border-color: #bbb;
}
// font-color
.i-tool-font-color, .i-tool-font-btn {
border: 1px solid #ddd;
//padding: 3px 7px;
border-radius: 6px;
width: 45px;
height: 31px;
background-color: white;
color: #555;
::ng-deep > span {
display: flex;
position: absolute; position: absolute;
top: 21px; left: 0;
left: 5px; right: 0;
top: 0;
bottom: 0;
padding: 3px 7px;
} }
} .i-left {
.i-dropdown-menu { .fa-font,.fa-bold,.fa-italic,.fa-strikethrough, .fa-underline {
width: 15px; font-size: 10px;
font-size: 10px; position: absolute;
border-left: 1px solid #ddd; color: #555;
display: flex; left: 8px;
align-items: center; top: 7px;
.anticon-down { }
transform: scale(0.6); .i-color {
width: 68%;
height: 5px;
background-color: black;
position: absolute;
top: 21px;
left: 5px;
}
}
.i-dropdown-menu {
width: 15px;
font-size: 10px;
border-left: 1px solid #ddd;
display: flex;
align-items: center;
.anticon-down {
transform: scale(0.6);
}
} }
} }
} .i-tool-font-btn{
.i-tool-font-btn{ width: 31px;
width: 31px; }
} .fa-icon{
.fa-icon{ width: 100%;
width: 100%; height: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
// bg-color
.i-tool-bg-color {
@include tool-btn();
padding: 0 9px;
::ng-deep > span {
display: flex; display: flex;
justify-content: center;
align-items: center; align-items: center;
cursor: pointer;
} }
// bg-color
.i-tool-bg-color {
@include tool-btn();
padding: 0 9px;
::ng-deep > span {
display: flex;
align-items: center;
}
.i-color { .i-color {
display: block; display: block;
width: 16px; width: 16px;
height: 16px; height: 16px;
background-color: white; background-color: white;
margin-left: 10px; margin-left: 10px;
}
} }
}
// horizontal-center // horizontal-center
.i-tool-horizontal-center { .i-tool-horizontal-center {
@include tool-btn(); @include tool-btn();
width: 37px; width: 37px;
}
} }
.p-box { .p-box {
width: 1280px; width: 1280px;
height: 720px; height: 720px;
...@@ -253,7 +203,9 @@ ...@@ -253,7 +203,9 @@
overflow: hidden; overflow: hidden;
} }
.p-sentence {
@include k-no-select();
}
.p-animation-index-box { .p-animation-index-box {
.i-animation-index { .i-animation-index {
...@@ -326,6 +278,7 @@ ...@@ -326,6 +278,7 @@
::ng-deep .ant-radio-button-wrapper { ::ng-deep .ant-radio-button-wrapper {
padding: 0 10px; padding: 0 10px;
@include k-no-select();
} }
.i-toolbox { .i-toolbox {
...@@ -356,6 +309,7 @@ ...@@ -356,6 +309,7 @@
cursor: pointer; cursor: pointer;
text-align: left; text-align: left;
display: flex; display: flex;
@include k-no-select();
} }
.i-active { .i-active {
background-color: antiquewhite; background-color: antiquewhite;
......
import { import {
Component, Component,
ElementRef, ElementRef,
...@@ -11,82 +10,6 @@ import { ...@@ -11,82 +10,6 @@ import {
ViewChild ViewChild
} from '@angular/core'; } from '@angular/core';
const editorTpl = `<html lang="en"><head><meta charset="utf-8">
<meta name="viewport"
content="width=device-width,initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"/>
<style>
@font-face{
font-family: 'BRLNSDB';
src: url("../../../assets/font/BRLNSDB.TTF") ;
}
@font-face{
font-family: 'BRLNSB';
src: url("../../../assets/font/BRLNSB.TTF") ;
}
@font-face{
font-family: 'BRLNSR';
src: url("../../../assets/font/BRLNSR.TTF") ;
}
@font-face{
font-family: 'GOTHIC';
src: url("../../../assets/font/GOTHIC.TTF") ;
}
@font-face{
font-family: 'GOTHICB';
src: url("../../../assets/font/GOTHICB.TTF") ;
}
@font-face{
font-family: 'GOTHICBI';
src: url("../../../assets/font/GOTHICBI.TTF") ;
}
@font-face{
font-family: 'GOTHICI';
src: url("../../../assets/font/GOTHICI.TTF") ;
}
@font-face{
font-family: 'MMTextBook';
src: url("../../../assets/font/MMTextBook.otf") ;
}
@font-face{
font-family: 'MMTextBook-Bold';
src: url("../../../assets/font/MMTextBook-Bold.otf") ;
}
@font-face{
font-family: 'MMTextBook-BoldItalic';
src: url("../../../assets/font/MMTextBook-BoldItalic.otf") ;
}
@font-face{
font-family: 'MMTextBook-Italic';
src: url("../../../assets/font/MMTextBook-Italic.otf") ;
}
html, body{
/*font-size: 30px;*/
}
body{
height:48px;
overflow: hidden;
margin: 0;
padding: 0 .5rem;
font-family: 'BRLNSB, BRLNSDB, BRLNSR, GOTHIC, GOTHICB, MMTextBook';
background: #FFF;
line-height: 48px;
}
</style>
</head>
<body>{{content}}</body>
</html>`;
@Component({ @Component({
selector: 'app-lesson-title-config', selector: 'app-lesson-title-config',
templateUrl: './lesson-title-config.component.html', templateUrl: './lesson-title-config.component.html',
...@@ -96,45 +19,22 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy, ...@@ -96,45 +19,22 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
fontFamilyList = [ fontFamilyList = [
'Arial', 'Arial',
'BRLNSB', 'ARBLI'
'BRLNSDB',
'BRLNSR',
'GOTHIC',
'GOTHICB',
// "GOTHICBI",
// "GOTHICI",
'MMTextBook',
// "MMTextBook-Bold",
// "MMTextBook-Italic",
// "MMTextBook-BoldItalic",
]; ];
colorList = [ colorList = [
'#000000', '#111111',
'#ffffff', '#ffffff',
'#595959', '#595959',
'#0075c2', '#0075c2',
'#c61c1e', '#c61c1e',
'#9cbc3a', '#9cbc3a'
'#008000',
'#FF0000',
'#D2691E',
]; ];
MIN_FONT_SIZE = 1; MIN_FONT_SIZE = 1;
MAX_FONT_SIZE = 7; MAX_FONT_SIZE = 7;
isShowFontColorPane = false; isShowFontColorPane = false;
isShowBGColorPane = false; isShowBGColorPane = false;
fontSizeRange = [ fontSizeRange: number[];
// {name: '1号', value: 9},
// {name: '2号', value: 13},
// {name: '3号', value: 16},
// {name: '4号', value: 18},
// {name: '5号', value: 24},
// {name: '6号', value: 32},
];
editorContent = ''; editorContent = '';
...@@ -145,17 +45,25 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy, ...@@ -145,17 +45,25 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
loopCnt = 0; loopCnt = 0;
maxLoops = 20; maxLoops = 20;
groupIconsCount = {
@ViewChild('titleEl', {static: true}) titleEl: ElementRef; a: Array.from(Array(11).keys()),
b: Array.from(Array(8).keys()),
c: Array.from(Array(8).keys()),
};
prevIcons = [];
prevType = '';
@ViewChild('titleEl') titleEl: ElementRef;
titleEW = null; titleEW = null;
@Input() @Input()
titleObj = { titleObj = {
type: 'a',
content: '', content: '',
icons: [],
audio_url: '' audio_url: ''
}; };
@Input()
withIcon = true;
@Output() @Output()
titleUpdated = new EventEmitter(); titleUpdated = new EventEmitter();
...@@ -176,12 +84,16 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy, ...@@ -176,12 +84,16 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
let defObj = this.titleObj; let defObj = this.titleObj;
if (!vars.titleObj.currentValue) { if (!vars.titleObj.currentValue) {
defObj = { defObj = {
type: 'a',
content: '', content: '',
icons: [],
audio_url: '' audio_url: ''
}; };
} else { } else {
defObj = vars.titleObj.currentValue; defObj = vars.titleObj.currentValue;
} }
this.titleObj.icons = defObj.icons || [];
this.titleObj.type = defObj.type || 'a';
this.titleObj.content = defObj.content || ''; this.titleObj.content = defObj.content || '';
this.titleObj.audio_url = defObj.audio_url || ''; this.titleObj.audio_url = defObj.audio_url || '';
this.titleEW.document.body.innerHTML = this.titleObj.content; this.titleEW.document.body.innerHTML = this.titleObj.content;
...@@ -190,23 +102,33 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy, ...@@ -190,23 +102,33 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
ngOnInit() { ngOnInit() {
if (!this.titleObj) { if (!this.titleObj) {
this.titleObj = { this.titleObj = {
type: 'a',
content: '', content: '',
icons: [],
audio_url: '' audio_url: ''
}; };
} }
this.titleObj.icons = this.titleObj.icons || [];
this.titleObj.type = this.titleObj.type || 'a';
this.titleObj.content = this.titleObj.content || ''; this.titleObj.content = this.titleObj.content || '';
this.titleObj.audio_url = this.titleObj.audio_url || ''; this.titleObj.audio_url = this.titleObj.audio_url || '';
this.editorContent = editorTpl.replace('{{content}}', this.titleObj.content) ; this.editorContent = `<html lang="en"><head><meta charset="utf-8">
<meta name="viewport"
content="width=device-width,initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"/>
</head>
<body style="height:48px;overflow: hidden;margin: 0;padding: 0 .5rem;background: #FFF;line-height: 48px;">
${this.titleObj.content}
</body>
</html>`;
this.titleEW = this.titleEl.nativeElement.contentWindow; this.titleEW = this.titleEl.nativeElement.contentWindow;
console.log('this.titleEW', this.titleEW);
const tdoc = this.titleEW.document; const tdoc = this.titleEW.document;
tdoc.designMode = 'on'; tdoc.designMode = "on";
tdoc.open('text/html', 'replace'); tdoc.open('text/html', 'replace');
tdoc.write(this.editorContent); tdoc.write(this.editorContent);
tdoc.close(); tdoc.close();
tdoc.addEventListener('keypress', this.keyPress, true); tdoc.addEventListener("keypress", this.keyPress, true);
tdoc.addEventListener('blur', () => { tdoc.addEventListener("blur", () => {
if (this.titleObj.content === this.titleEW.document.body.innerHTML.trim()) { if (this.titleObj.content === this.titleEW.document.body.innerHTML.trim()) {
return; return;
} }
...@@ -237,7 +159,30 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy, ...@@ -237,7 +159,30 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
ngOnDestroy(): void { ngOnDestroy(): void {
} }
iconsChanges(val) {
let a = this.titleObj.icons;
let b = val;
if (a.length > b.length) {
const diff = a.filter(x => !b.includes(x));
const ti = [...this.titleObj.icons];
for (let i = 0; i < diff.length; i++) {
const d = diff[i];
const idx = ti.indexOf(d);
ti.splice(idx, 1);
}
this.titleObj.icons = ti;
} else {
const diff = b.filter(x => !a.includes(x));
this.titleObj.icons = [...this.titleObj.icons, ...diff];
}
this.shouldSave();
}
typeChange(val) {
this.titleObj.icons = [];
this.shouldSave();
}
keyPress(evt) { keyPress(evt) {
try { try {
...@@ -250,9 +195,9 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy, ...@@ -250,9 +195,9 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
const key = String.fromCharCode(evt.charCode).toLowerCase(); const key = String.fromCharCode(evt.charCode).toLowerCase();
let cmd = ''; let cmd = '';
switch (key) { switch (key) {
case 'b': cmd = 'bold'; break; case 'b': cmd = "bold"; break;
case 'i': cmd = 'italic'; break; case 'i': cmd = "italic"; break;
case 'u': cmd = 'underline'; break; case 'u': cmd = "underline"; break;
} }
...@@ -269,13 +214,10 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy, ...@@ -269,13 +214,10 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
alert(e); alert(e);
} }
} }
execEditorCommand(command, option?: any) { execEditorCommand(command, option?: any) {
console.log('sssss');
try { try {
this.titleEW.focus(); this.titleEW.focus();
const result = this.titleEW.document.execCommand(command, false, option); this.titleEW.document.execCommand(command, false, option);
console.log(result);
this.loopCnt = 0; this.loopCnt = 0;
return false; return false;
...@@ -287,7 +229,7 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy, ...@@ -287,7 +229,7 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
}, 100); }, 100);
this.loopCnt += 1; this.loopCnt += 1;
} else { } else {
alert('Error executing command.'); alert("Error executing command.");
} }
} }
} }
...@@ -300,7 +242,7 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy, ...@@ -300,7 +242,7 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
this.execEditorCommand('forecolor', this.__fontColor); this.execEditorCommand('forecolor', this.__fontColor);
} }
onChangeFontFamily(font) { onChangeFontFamily(font) {
this.execEditorCommand('fontName', font); this.execEditorCommand('fontname', font);
} }
onChangeFontSize(size?: any) { onChangeFontSize(size?: any) {
...@@ -330,10 +272,9 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy, ...@@ -330,10 +272,9 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
this.titleUpdated.emit(this.titleObj); this.titleUpdated.emit(this.titleObj);
} }
shouldSave = () => { shouldSave = () => {
console.log('title shouldSave', this.titleObj); console.log('title shouldSave');
this.titleObj.content = this.titleEW.document.body.innerHTML.trim(); this.titleObj.content = this.titleEW.document.body.innerHTML.trim();
this.titleUpdated.emit(this.titleObj); this.titleUpdated.emit(this.titleObj);
} }
} }
@import '../../style/common_mixin.css'; @import '../../style/common_mixin';
.cmp-player-content-wrapper{ .cmp-player-content-wrapper{
max-height: 100%; max-height: 100%;
......
import { import {
AfterViewInit, AfterViewInit,
Component, Component,
ElementRef, ElementRef,
Input, Input,
OnChanges, OnChanges,
OnDestroy, OnDestroy,
OnInit, OnInit,
ViewChild ViewChild
} from '@angular/core'; } from '@angular/core';
@Component({ @Component({
...@@ -18,21 +18,21 @@ import { ...@@ -18,21 +18,21 @@ import {
export class PlayerContentWrapperComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit { export class PlayerContentWrapperComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
@ViewChild('wrapperEl', {static: true }) wrapperEl: ElementRef; @ViewChild('wrapperEl') wrapperEl: ElementRef;
// // aspect ratio? // // aspect ratio?
@Input() ratio; @Input() ratio;
_w: string; _w: string;
_h: string; _h: string;
constructor() { constructor() {
if (window.innerHeight < window.innerWidth) { if (window.innerHeight < window.innerWidth) {
this._h = '100%'; this._h = '100%';
this._w = 'auto'; this._w = 'auto';
} else { } else {
this._w = '100%'; this._w = '100%';
this._h = 'auto'; this._h = 'auto';
} }
} }
ngOnInit() { ngOnInit() {
if (!this.ratio) { if (!this.ratio) {
......
<div class="position-relative"> <div class="position-relative">
<nz-upload class="p-image-uploader" [nzDisabled]="disableUpload" <nz-upload class="p-image-uploader" [nzDisabled]="disableUpload"
[nzShowUploadList]="false" [nzShowUploadList]="false"
nzAccept = "image/*" nzAccept = "image/*"
[nzAction]="uploadUrl" [nzAction]="uploadUrl"
[nzData]="uploadData" [nzData]="uploadData"
(nzChange)="handleChange($event)"> (nzChange)="handleChange($event)">
<!--[nzBeforeUpload]="customUpload">-->
<div class="p-box d-flex align-items-center"> <div class="p-box d-flex align-items-center">
<div class="p-upload-icon" *ngIf="!picUrl && !uploading"> <div class="p-upload-icon" *ngIf="!picUrl && !uploading">
<i nz-icon nzType="cloud-upload" nzTheme="outline" [style.font-size]="iconSize + 'em'"></i> <i nz-icon type="cloud-upload" theme="outline" [style.font-size]="iconSize + 'em'"></i>
<div class="m-3"></div> <div class="m-3"></div>
<span>{{TIP}}</span> <span>{{TIP}}</span>
<!--<div class="mt-5 p-progress-bar" *ngIf="uploading">-->
<!--<div class="p-progress-bg" [style.width]="progress*0.2+'rem'"></div>-->
<!--<div class="p-progress-value">{{progress}}%</div>-->
<!--</div>-->
</div> </div>
<div class="p-upload-progress-bg" *ngIf="uploading"> <div class="p-upload-progress-bg" *ngIf="uploading">
<div class="i-bg" [style.width]="progress+'%'"></div> <div class="i-bg" [style.width]="progress+'%'"></div>
<div class="i-text"> <div class="i-text">
<fa-icon icon="cloud-upload-alt"></fa-icon> <fa name="cloud-upload"></fa>
Uploading... Uploading...
</div> </div>
</div> </div>
<div class="p-preview" *ngIf="!uploading && picUrl " <div class="p-preview" *ngIf="!uploading && picUrl "
[style.background-image]="picUrl | backgroundImage "> [style.background-image]="picUrl | backgroundImage ">
</div> </div>
</div> </div>
</nz-upload> </nz-upload>
<div class="p-btn-delete" *ngIf="canDelete" <div class="p-btn-delete" *ngIf="canDelete"
nz-popconfirm nzTitle="Are you sure ?" nz-popconfirm nzTitle="Are you sure ?"
(nzOnConfirm)="onDelete()" (nzOnConfirm)="onDelete()"
> >
<i nz-icon nzType="close" nzTheme="outline"></i> <i nz-icon type="close" theme="outline"></i>
</div> </div>
</div> </div>
@import '../../style/common_mixin.css'; @import '../../style/common_mixin';
.p-image-uploader { .p-image-uploader {
position: relative; position: relative;
...@@ -52,15 +52,10 @@ ...@@ -52,15 +52,10 @@
.p-preview { .p-preview {
width: 100%; width: 100%;
height: 100%; height: 100%;
background-size: contain;
background-repeat: no-repeat;
background-position: 50% 50%;
//background-image: url("https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"); //background-image: url("https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png");
@include k-img-bg();
} }
} }
.d-flex{
display: flex;
}
} }
.p-btn-delete { .p-btn-delete {
......
...@@ -29,19 +29,10 @@ export class UploadImageWithPreviewComponent implements OnDestroy, OnChanges { ...@@ -29,19 +29,10 @@ export class UploadImageWithPreviewComponent implements OnDestroy, OnChanges {
@Input() @Input()
disableUpload = false; disableUpload = false;
uploadUrl; uploadUrl = (<any> window).courseware.uploadUrl();
uploadData; uploadData = (<any> window).courseware.uploadData();
constructor(private nzMessageService: NzMessageService) { constructor(private nzMessageService: NzMessageService) {
this.uploadUrl = (<any> window).courseware.uploadUrl();
this.uploadData = (<any> window).courseware.uploadData();
window['air'].getUploadCallback = (url, data) => {
this.uploadUrl = url;
this.uploadData = data;
};
} }
ngOnChanges() { ngOnChanges() {
if (!this.picItem) { if (!this.picItem) {
...@@ -54,9 +45,6 @@ export class UploadImageWithPreviewComponent implements OnDestroy, OnChanges { ...@@ -54,9 +45,6 @@ export class UploadImageWithPreviewComponent implements OnDestroy, OnChanges {
handleChange(info: { type: string, file: UploadFile, event: any }): void { handleChange(info: { type: string, file: UploadFile, event: any }): void {
console.log('info:' , info);
switch (info.type) { switch (info.type) {
case 'start': case 'start':
// this.isUploading = true; // this.isUploading = true;
......
<div class="p-video-box">
<div class="up-video" style="display: flex;"> <div class="up-video" style="display: flex;">
<!--<nz-upload class="" [nzDisabled]="!showUploadBtn"--> <!--<nz-upload class="" [nzDisabled]="!showUploadBtn"-->
<!--[nzShowUploadList]="false"--> <!--[nzShowUploadList]="false"-->
...@@ -16,7 +16,8 @@ ...@@ -16,7 +16,8 @@
<button type="button" nz-button nzType="default" *ngIf="showUploadBtn" [disabled]="uploading" <button type="button" nz-button nzType="default" *ngIf="showUploadBtn" [disabled]="uploading"
[nzLoading]="uploading" > [nzLoading]="uploading" >
<i nz-icon nzType="plus" nzTheme="outline"></i> <i nz-icon type="plus" theme="outline"></i>
<span>{{ uploading ? 'Uploading' : 'Select Video' }}</span> <span>{{ uploading ? 'Uploading' : 'Select Video' }}</span>
<!--<span>Select Video</span>--> <!--<span>Select Video</span>-->
</button> </button>
...@@ -55,9 +56,9 @@ ...@@ -55,9 +56,9 @@
</div> </div>
<div class="p-box d-flex align-items-center p-video-uploader"> <div class="p-box d-flex align-items-center p-video-uploader" style="top: 20px;">
<div class="p-upload-icon" *ngIf="!showUploadBtn && !videoUrl && !uploading"> <div class="p-upload-icon" *ngIf="!showUploadBtn && !videoUrl && !uploading">
<i nz-icon nzType="upload" nzTheme="outline"></i> <i nz-icon type="upload" theme="outline"></i>
<div class="m-3"></div> <div class="m-3"></div>
<span>Click here to upload video</span> <span>Click here to upload video</span>
<div class="mt-5 p-progress-bar" *ngIf="uploading"> <div class="mt-5 p-progress-bar" *ngIf="uploading">
...@@ -69,26 +70,26 @@ ...@@ -69,26 +70,26 @@
[ngClass]="{'smart-bar': showUploadBtn}" > [ngClass]="{'smart-bar': showUploadBtn}" >
<div class="i-bg" [style.width]="progress+'%'"></div> <div class="i-bg" [style.width]="progress+'%'"></div>
<div class="i-text"> <div class="i-text">
<fa-icon icon="cloud-upload-alt"></fa-icon> <fa name="cloud-upload"></fa>
Uploading... Uploading...
</div> </div>
</div> </div>
<div class="p-upload-check-bg" *ngIf="checking"> <div class="p-upload-check-bg" *ngIf="checking">
<div class="i-bg" [style.width]="progress+'%'"></div> <div class="i-bg" [style.width]="progress+'%'"></div>
<div class="i-text"> <div class="i-text">
<fa-icon icon="cloud-upload-alt"></fa-icon> <fa name="cloud-upload"></fa>
<i nz-icon nzType="loading" nzTheme="outline"></i>Checking... <i nz-icon type="loading" theme="outline"></i>Checking...
</div> </div>
</div> </div>
<div class="p-preview" *ngIf="!uploading && videoUrl " > <div class="p-preview" *ngIf="!showUploadBtn && !uploading && videoUrl " >
<!--<video crossorigin="anonymous" [src]="videoUrl" controls #videoNode></video>--> <!--<video crossorigin="anonymous" [src]="videoUrl" controls #videoNode></video>-->
<video [src]="safeVideoUrl(videoUrl)" controls #videoNode></video> <video [src]="safeVideoUrl(videoUrl)" controls #videoNode (loadedmetadata)="videoLoadedMetaData()"></video>
</div> </div>
</div> </div>
<div [style.display]="!checkVideoExists?'none':''"> <div [style.display]="!checkVideoExists?'none':''">
<span><i nz-icon nzType="loading" nzTheme="outline"></i> checking file to upload</span> <span><i nz-icon type="loading" theme="outline"></i> checking file to upload</span>
</div>
</div> </div>
@import '../../style/common_mixin.css'; @import '../../style/common_mixin';
/*.p-video-box{
bottom: 0;
border: 2px dashed #ddd;
border-radius: 0.5rem;
background-color: #fafafa;
text-align: center;
color: #aaa;
padding-top: 56.25%;
//font-size: 4rem;
position: relative;
.p-upload-icon{
left: 50%;
position: absolute;
top: 50%;
transform: translate(-50% ,-50%);
}
}*/
.p-video-uploader { .p-video-uploader {
position: relative; position: relative;
display: block; display: block;
...@@ -33,56 +17,50 @@ ...@@ -33,56 +17,50 @@
background-color: #fafafa; background-color: #fafafa;
text-align: center; text-align: center;
color: #aaa; color: #aaa;
.p-upload-icon {
text-align: center;
margin: auto;
.anticon-upload {
color: #888;
font-size: 5rem;
}
.p-progress-bar {
position: relative;
width: 20rem;
height: 1.5rem;
border: 1px solid #ccc;
border-radius: 1rem;
.p-progress-bg {
background-color: #1890ff;
border-radius: 1rem;
height: 100%;
}
.p-progress-value {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-shadow: 0 0 4px #000;
color: white;
text-align: center;
font-size: 0.9rem;
line-height: 1.5rem;
}
}
}
.p-preview {
width: 100%;
height: 100%;
//background-image: url("https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png");
video{
max-height: 100%;
max-width: 100%;
}
}
} }
} }
.p-upload-icon {
text-align: center;
margin: auto;
}
.p-upload-icon .anticon-upload {
color: #888;
font-size: 5rem;
}
p-progress-bar {
position: relative;
width: 20rem;
height: 1.5rem;
border: 1px solid #ccc;
border-radius: 1rem;
}
.p-progress-bar .p-progress-bg {
background-color: #1890ff;
border-radius: 1rem;
height: 100%;
}
.p-progress-bar .p-progress-value {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-shadow: 0 0 4px #000;
color: white;
text-align: center;
font-size: 0.9rem;
line-height: 1.5rem;
}
.p-preview {
width: 100%;
height: 100%;
//background-image: url("https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png");
}
.p-preview video{
max-height: 100%;
max-width: 100%;
position: absolute;
display: flex;
}
.p-btn-delete { .p-btn-delete {
position: absolute; position: absolute;
right: -0.5rem; right: -0.5rem;
......
import {Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Output, SecurityContext, ViewChild} from '@angular/core'; import {Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Output, SecurityContext, ViewChild} from '@angular/core';
import {NzMessageService, UploadChangeParam, UploadFile, UploadFileStatus} from 'ng-zorro-antd'; import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {DomSanitizer, SafeResourceUrl} from '@angular/platform-browser'; import {DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';
...@@ -24,7 +24,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy { ...@@ -24,7 +24,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
@Input() @Input()
videoUrl = ''; videoUrl = '';
@ViewChild('videoNode', {static: true }) @ViewChild('videoNode')
videoNode: ElementRef; videoNode: ElementRef;
...@@ -47,8 +47,8 @@ export class UploadVideoComponent implements OnChanges, OnDestroy { ...@@ -47,8 +47,8 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
item: any; item: any;
// videoItem = null; // videoItem = null;
uploadUrl; uploadUrl = (<any> window).courseware.uploadUrl();
uploadData; uploadData = (<any> window).courseware.uploadData();
constructor(private nzMessageService: NzMessageService, constructor(private nzMessageService: NzMessageService,
private sanitization: DomSanitizer private sanitization: DomSanitizer
...@@ -58,16 +58,6 @@ export class UploadVideoComponent implements OnChanges, OnDestroy { ...@@ -58,16 +58,6 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
this.uploading = false; this.uploading = false;
this.videoFile = null; this.videoFile = null;
this.uploadUrl = (<any> window).courseware.uploadUrl();
this.uploadData = (<any> window).courseware.uploadData();
window['air'].getUploadCallback = (url, data) => {
this.uploadUrl = url;
this.uploadData = data;
};
} }
ngOnChanges() { ngOnChanges() {
// if (!this.videoFile || this.showUploadBtn) { // if (!this.videoFile || this.showUploadBtn) {
...@@ -81,7 +71,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy { ...@@ -81,7 +71,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
} }
safeVideoUrl(url) { safeVideoUrl(url) {
console.log(url); console.log(url)
return this.sanitization.bypassSecurityTrustResourceUrl(url); // `${url}`; return this.sanitization.bypassSecurityTrustResourceUrl(url); // `${url}`;
} }
videoLoadedMetaData() { videoLoadedMetaData() {
...@@ -89,7 +79,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy { ...@@ -89,7 +79,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
} }
handleChange(info: UploadChangeParam/* { type: string, file: UploadFile, event: any }*/): void { handleChange(info: { type: string, file: UploadFile, event: any }): void {
console.log('info:' , info); console.log('info:' , info);
...@@ -119,7 +109,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy { ...@@ -119,7 +109,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
break; break;
case 'progress': case 'progress':
this.progress = info.event.percent; this.progress = parseInt(info.event.percent, 10);
this.doProgress(this.progress); this.doProgress(this.progress);
break; break;
} }
...@@ -162,9 +152,9 @@ export class UploadVideoComponent implements OnChanges, OnDestroy { ...@@ -162,9 +152,9 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
if (duration) { if (duration) {
duration = duration * 1000; duration = duration * 1000;
} }
file.height = height; file['height'] = height;
file.width = width; file['width'] = width;
file.duration = duration; file['duration'] = duration;
vid.preload = 'none'; vid.preload = 'none';
vid.src = ''; vid.src = '';
vid.remove(); vid.remove();
......
@import '../style/common_mixin.css';
.model-content {
width: 100%;
height: 100%;
}
<div class="model-content"> <div class="model-content">
<div class="card-config">
<div *ngFor="let item of contentObj.dataArray; let i = index" class="card-item" style="padding: 0.5vw;" >
<div style="position: absolute; left: 200px; top: 100px; width: 800px;"> <div class="card-item-content border">
<div class="card-item-content">
<input type="text" nz-input [(ngModel)]="item.text" (blur)="save()"> <div class="title" >
糖果 -<strong>{{ i + 1 }}</strong>-
<app-upload-image-with-preview </div>
[picUrl]="item.pic_url" <div class="section" >
(imageUploaded)="onImageUploadSuccess($event, 'pic_url')" <div class="section-content">
></app-upload-image-with-preview> <div style="flex:1">
<div style="display: flex; margin-bottom: 10px;">
<app-audio-recorder <div style="flex:2">
[audioUrl]="item.audio_url" 音频
(audioUploaded)="onAudioUploadSuccess($event, 'audio_url')" </div>
></app-audio-recorder> <div style="flex:7">
<app-custom-hot-zone></app-custom-hot-zone> <app-audio-recorder [audioUrl]="item.audio_url" (audioUploaded)="onUploadSuccessByItem($event, item, 'audio_url')" (beforePlaying)="stopAllAudio(i)"></app-audio-recorder>
<app-upload-video></app-upload-video> </div>
<app-lesson-title-config></app-lesson-title-config> </div>
</div>
<div style="flex:1" >
<div style="display: flex; margin-bottom: 10px;">
<div style="flex:2">
显示选项
</div>
<div style="flex:7">
<nz-radio-group [(ngModel)]="item.type" (ngModelChange)="saveItem()" >
<label nz-radio [nzValue]="'Text'">文字</label>
<label nz-radio [nzValue]="'Image'">图片</label>
</nz-radio-group>
</div>
</div>
</div>
<div *ngIf="item.type=='Text'" style="flex:1">
<div style="display: flex; margin-bottom: 10px;">
<div style="flex:2">
文字
</div>
<div style="flex:7">
<input type="text" nz-input placeholder="" [(ngModel)]="item.text" (blur)="saveItem()" />
</div>
</div>
</div>
<div *ngIf="item.type=='Image'" style="flex:1">
<div style="display: flex;">
<div style="flex:2">
图片
</div>
<div style="flex:7;">
<div style="width: 300px;">
<app-upload-image-with-preview [picUrl]="item.image_url" (imageUploaded)="onUploadSuccessByItem($event, item, 'image_url')"></app-upload-image-with-preview>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="section" style="height: 40px;" >
<!-- <div style="float:right; text-align: left; padding-left: 20px;">
<button style="flex:1;" nz-button nzType="default" (click)="handleMoveItemUp(i)" [disabled]="i==0">
<i nz-icon nzType="up" nzTheme="outline" style="float: left; margin-top: 4px;"></i>
<span style="float: right;">上移</span>
</button>
<button style="flex:1; margin-left: 10px; vertical-align:baseline;" nz-button nzType="default" (click)="handleMoveItemDown(i)" [disabled]="i==contentObj.dataArray.length-1">
<i nz-icon nzType="down" nzTheme="outline" style="float: left; margin-top: 4px;"></i>
<span style="float: right;">下移</span>
</button>
</div> -->
<div style="float:right; text-align: right; padding-right: 20px;">
<button style="margin-bottom: 10px;" nz-button nzType="danger" (click)="deleteItem(i)" >
<span>删除</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div *ngIf="contentObj.dataArray.length<4" class="card-item" style="padding: 0.5vw; width: 500px;" >
<button nz-button nzType="primary" class="add-btn" (click)="addItem()">
<i nz-icon nzType="plus-circle" nzTheme="outline"></i>
新建卡片
</button>
</div> </div>
</div> </div>
\ No newline at end of file
@import "../style/common_mixin";
.model-content {
margin: 10px;
.card-config {
// width: 100%;
height: 100%;
// display: flex;
flex-wrap: wrap;
box-sizing: border-box;
// width: 500px;
.card-item{
margin-bottom: 40px;
.border {
border-radius: 20px;
border-style: dashed;
padding:20px;
width: 100%;
}
.card-item-content{
.title {
font-size: 24px;
width: 100%;
text-align: center;
}
.section{
border-top: 1px solid ;
padding: 10px 0;
.section-title{
font-size: 24px;
width: 100%;
}
.section-content{
display: flex;
flex-direction: row;
margin: 5px 0 10px 0;
}
}
.pic-sound-box {
width: 50%;
display: flex;
flex-direction: column;
}
.add-btn-box {
display: flex;
align-items: center;
justify-content: center;
height: 20vw;
padding: 10px;
padding-top: 5vw;
}
}
}
}
}
.hidden{
display: none;
}
import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef} from '@angular/core'; import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef} from '@angular/core';
import defauleFormData from '../../assets/play/default/formData/defaultData.js'
@Component({ @Component({
selector: 'app-form', selector: 'app-form',
templateUrl: './form.component.html', templateUrl: './form.component.html',
styleUrls: ['./form.component.css'] styleUrls: ['./form.component.scss']
}) })
export class FormComponent implements OnInit, OnChanges, OnDestroy {
// 储存数据用 export class FormComponent implements OnInit, OnChanges, OnDestroy {
saveKey = "test_0011";
// 储存对象
item;
_item: any;
dataArray: Array<Object> = [];
contentObj = {}
constructor(private appRef: ApplicationRef,private changeDetectorRef: ChangeDetectorRef) { KEY = 'DataKey_East_L226';
set item(item) {
this._item = item;
}
get item() {
return this._item;
} }
@Output()
update = new EventEmitter();
constructor(private appRef: ApplicationRef) {
ngOnInit() { }
ngOnInit() {
this.item = {}; this.item = {};
this.item.contentObj = {};
// 获取存储的数据 const getData = (<any> window).courseware.getData;
(<any> window).courseware.getData((data) => { getData((data) => {
// console.log("读取数据", data)
if (data) { if (data) {
this.item = data; this.item = data;
} else {
this.item = {};
}
if ( !this.item.contentObj ) {
this.item.contentObj = {};
} }
this.init(); this.init();
this.changeDetectorRef.markForCheck();
this.changeDetectorRef.detectChanges();
this.refresh(); this.refresh();
}, this.KEY);
}
ngOnChanges() {
}, this.saveKey); }
ngOnDestroy() {
} }
saveData(e){
this.save();
}
ngOnChanges() { init() {
if (Object.keys(this.item.contentObj).length != 0 && this.item.contentObj.version && this.item.contentObj.version==defauleFormData.version) {
// console.log("读取数据", this.item.contentObj)
this.contentObj = this.item.contentObj;
this.dataArray = this.item.contentObj.dataArray;
} else {
this.contentObj = defauleFormData;
// console.log("使用默认数据", this.contentObj)
this.item.contentObj = this.contentObj;
}
} }
ngOnDestroy() { cardItemData(){
return {
type: "Text",
text: "",
audio_url: "",
image_url: ""
};
} }
cardChoiceData(){
return { isText: true, text: "", image_url: "" }
}
getDefaultPicArr() {
let arr = [];
return arr;
}
init() { initData() {
} }
/** addChoice(questionIndex) {
* 储存图片数据 // let item = this.cardChoiceData();
* @param e // this.dataArray[questionIndex].choice.incorrect.push(item);
*/ // this.saveItem();
onImageUploadSuccess(e, key) { }
this.item[key] = e.url; onUploadSuccessByItem(e, item, key) {
this.save(); item[key] = e.url;
this.save();
} }
/** onImageUploadSuccessByItem(e, item) {
* 储存音频数据 item.image_url = e.url
* @param e this.save();
*/ }
onAudioUploadSuccess(e, key) {
onAudioUploadSuccessByItem(e, item, key) {
item[key] = e.url;
this.save();
}
this.item[key] = e.url; onTitleAudioUploadSuccess(e) {
this.item.contentObj.titleAudio_url = e.url;
this.save(); this.save();
} }
addItem() {
let item = this.cardItemData();
this.dataArray.push(item);
this.saveItem();
}
deleteItem(index){
this.dataArray.splice(index,1)
this.save()
}
radioClick(it, radioValue) {
it.radioValue = radioValue;
this.saveItem();
}
clickCheckBox() {
this.saveItem();
}
saveItem() {
this.save();
}
/**
* 储存数据
*/
save() { save() {
(<any> window).courseware.setData(this.item, null, this.saveKey); (<any> window).courseware.setData(this.item, null, this.KEY);
this.refresh(); this.refresh();
console.log("保存", this.item)
} }
/**
* 刷新 渲染页面
*/
refresh() { refresh() {
setTimeout(() => { setTimeout(() => {
this.appRef.tick(); this.appRef.tick();
}, 1); }, 1);
} }
} }
import {
MySprite,
getMinScale,
ShapeRect,
tweenChange,
randomSortByArr,
Label,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem,
ShapeRectNew,
waterWave,
ShapeCircle,
MyAnimation
} from "./Unit";
import { matchesElement } from '@angular/animations/browser/src/render/shared';
export class Cartoon {
// 系统缩放比例
mapScale = 1;
stageWidth;
stageHeight;
clientWidth;
clientHeight;
// 音乐 和 图片的缓冲区
audio = new Map();
images = new Map();
imagesOriginSize = new Map();
// 坐标原点 包含缩放
originX = 0;
originY = 0;
setOrigin = (x, y) => {
this.originX = x;
this.originY = y;
}
getOrigin = () => {
return {
x: this.originX,
y: this.originY
}
}
// 相对坐标原点 包含缩放 用于添加孩子动画元素
relativeOriginX = 0;
relativeOriginY = 0;
setRelativeOrigin = (x, y) => {
this.relativeOriginX = x;
this.relativeOriginY = y;
}
getRelativeOrigin = () => {
return {
x: this.relativeOriginX,
y: this.relativeOriginY
}
}
// 存放音乐和图片的地址
audioObj = {}
imageObj = {}
_currentPlayAudio;
// 添加音乐
addAudio = (key, url) => {
this.audioObj[key] = url
};
// 添加音乐
addImage = (key, url) => {
this.imageObj[key] = url
};
// 播放音乐
_playingNow = []
audioCallback = {}
playAudio = function (key, now = false, callback = null, loop?, onplayingCallback?) {
const audio = this.audio.get(key);
if (audio) {
if (now) {
audio.pause();
audio.currentTime = 0;
}
this.audioCallback[key] = {}
if (callback) {
this.audioCallback[key]["onended"] = () => {
callback && callback()
}
audio.onended = () => {
let index = this._playingNow.indexOf(audio)
if (index != -1) {
this._playingNow.splice(index, 1)
}
callback();
};
}
if (onplayingCallback) {
this.audioCallback[key]["onplaying"] = () => {
onplayingCallback && onplayingCallback(audio)
}
audio.onplaying = () => {
onplayingCallback && onplayingCallback(audio)
}
}
audio.play();
audio.callback = callback
audio.loop = loop ? true : false
this._playingNow.push(audio)
this._currentPlayAudio = audio;
}
return audio
}
setAudioVolume(key, volume) {
if (volume < 0 || volume > 1) {
return
}
const audio = this.audio.get(key);
audio.volume = volume
}
stopAllAudio(audioAll?) {
if (!audioAll) {
audioAll = this._playingNow
}
audioAll.forEach(audio => {
if (audio) {
const audio_URL = audio.src
try {
if (audio) {
audio.onended && audio.onended()
audio.pause && audio.pause();
audio.currentTime = 0;
} else {
if (this.audioCallback[audio_URL] && this.audioCallback[audio_URL]["onended"]) {
this.audioCallback[audio_URL]["onended"]()
}
}
} catch (err) {
console.log(err)
}
}
else if (this._currentPlayAudio) {
this._currentPlayAudio.pause();
this._currentPlayAudio.currentTime = 0;
}
})
this._playingNow = []
}
stopAudio(audio_URL?) {
if (audio_URL) {
const audio = this.audio.get(audio_URL);
try {
if (audio) {
audio.onended && audio.onended()
audio.pause();
audio.currentTime = 0;
} else {
if (this.audioCallback[audio_URL] && this.audioCallback[audio_URL]["onended"]) {
this.audioCallback[audio_URL]["onended"]()
}
}
} catch (err) {
console.log(err)
}
}
else if (this._currentPlayAudio) {
this._currentPlayAudio.pause();
this._currentPlayAudio.currentTime = 0;
}
}
pauseAudio(key) {
const audio = this.audio.get(key);
audio.pause()
}
// 异步加载图片 音频资源
loadResources = () => {
const pr = [];
for (let key in this.imageObj) {
const p = this.preloadImage(this.imageObj[key]).then((img: any) => {
this.images.set(key, img);
this.imagesOriginSize.set(key, { width: img.width, height: img.height });
}).catch(err => console.log(key));
pr.push(p);
};
for (let key in this.audioObj) {
const a = this.preloadAudio(this.audioObj[key]).then((audio: any) => {
this.audio.set(key, audio);
}).catch(err => console.log(key));
pr.push(a);
};
return Promise.all(pr);
}
// 预加载图片
preloadImage = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
}
// 预加载音频
preloadAudio = (url) => {
return new Promise((resolve, reject) => {
const audio = new Audio();
audio.oncanplay = a => {
resolve(audio);
};
audio.onerror = () => {
reject();
};
audio.src = url;
audio.load();
});
}
// 缓存页面元素
cartoonElementsBuffer = {}
createCartoonElement = (key, type) => {
this.cartoonElementsBuffer[key] = {
ref: null,
get boundingBox(){
return this.ref.getBoundingBox()
}
}
this.cartoonElementsBuffer[key].id = key;
switch (type) {
case "MySprite": this.cartoonElementsBuffer[key].ref = new MySprite(); break;
case "ShapeRect": this.cartoonElementsBuffer[key].ref = new ShapeRect(); break;
case "ShapeRectNew": this.cartoonElementsBuffer[key].ref = new ShapeRectNew(); break;
case "Label": this.cartoonElementsBuffer[key].ref = new Label(); break;
case "waterWave": this.cartoonElementsBuffer[key].ref = new waterWave(); break;
case "ShapeCircle": this.cartoonElementsBuffer[key].ref = new ShapeCircle(); break;
default: this.cartoonElementsBuffer[key].ref = new MySprite(); break;
}
this.cartoonElementsBuffer[key].ref.id = key;
return this.cartoonElementsBuffer[key]
}
// 创建图片
createCartoonElementImage(id: string, image: string, width: number, height: number, initX: number, initY: number, withScale?: boolean) {
let element = this.createCartoonElement(id, "MySprite")
element.ref.init(this.images.get(image))
element.initX = initX
element.initY = initY
if (withScale) {
element.initScaleX = width * this.mapScale / element.ref.width
element.initScaleY = height * this.mapScale / element.ref.height
} else {
element.initScaleX = width / element.ref.width
element.initScaleY = height / element.ref.height
}
element.ref.scaleX = element.initScaleX
element.ref.scaleY = element.initScaleY
element.ref.x = element.initX
element.ref.y = element.initY
this.attachProperties(element)
return this.cartoonElementsBuffer[id]
}
// 创建图片(回调方式)
createCartoonElementImageFunc(id: string, image: string, callbackScale: Function, callbackPosition: Function) {
let element = this.createCartoonElement(id, "MySprite")
element.ref.init(this.images.get(image))
element.rePosition = () => {
let scale = callbackScale(element.ref.width, element.ref.height)
let position = callbackPosition(element.ref.width, element.ref.height)
// save initScale
element.ref.initScaleX = scale.sx
element.ref.initScaleY = scale.sy
element.initScaleX = scale.sx
element.initScaleY = scale.sy
// save initX_Y
element.ref.initX = position.x
element.ref.initY = position.y
element.initX = position.x
element.initY = position.y
// save initRotation
element.ref.initRotation = element.rotation ? element.rotation : 0
element.initRotation = element.rotation ? element.rotation : 0
element.ref.scaleX = scale.sx
element.ref.scaleY = scale.sy
element.ref.x = element.initX
element.ref.y = element.initY
}
element.rePosition()
this.attachProperties(element)
return this.cartoonElementsBuffer[id]
}
createCartoonElementLabel(id: string, text: string, fontName?: string, fontColor?: string, fontSize?: number, initX?: number, initY?: number) {
if (!fontName) {
fontName = "BRLNSDB"
}
if (!fontColor) {
fontColor = "#000000"
}
if (!fontSize) {
fontSize = 20
}
if (!initX) {
initX = 0
}
if (!initY) {
initY = 0
}
let element = this.createCartoonElement(id, "Label")
element.ref.text = text
element.ref.fontName = fontName
element.ref.fontColor = fontColor
element.ref.fontSize = fontSize
element.ref.x = initX
element.ref.y = initY
element.ref.textAlign = "center"
element.ref.refreshSize();
this.attachProperties(element)
return element
}
createCartoonElementLabelFunc(id: string, text: string, fontName?: string, fontColor?: string, fontSize?: number, callback?) {
let element = this.createCartoonElement(id, "Label")
element.ref.text = text
element.ref.fontName = fontName
element.ref.fontColor = fontColor
element.ref.fontSize = fontSize
element.ref.textAlign = "center"
element.ref.refreshSize();
if (callback) {
let size = callback(element.ref.width, element.ref.height)
element.ref.x = size.x
element.ref.y = size.y
}
return element
}
createLabel = (text, fontName, fontColor, fontSize, initX?, initY?) => {
let element = new Label()
element.text = text;
if (fontName) {
element.fontName = fontName;
}
if (fontColor) {
element.fontColor = fontColor;
}
if (fontSize) {
element.fontSize = fontSize;
}
element.textAlign = "center";
element.x = initX;
element.y = initY;
return element
}
createImage(image, callbackScale, callbackPosition) {
let element = new MySprite()
element.init(this.images.get(image))
let scale = callbackScale(element.width, element.height)
let position = callbackPosition(element.width, element.height)
element.scaleX = scale.sx
element.scaleY = scale.sy
element.x = position.x
element.y = position.y
return element
}
createBorder(config) {
let element = new ShapeRectNew()
if(config.width) element.width = config.width
if(config.height) element.height = config.height
if(config.x) element.x = config.x
if(config.y) element.y =config.y
if(config.borderColor && config.lineWidth) element.setOutLine(config.borderColor, config.lineWidth)
if(config.fill){
element.fill = true
}else{
element.fill = false
}
if(config.radius) element.radius = config.radius
return element
}
createRectangula(config) {
let element = new ShapeRectNew()
element.fill = true
if(config.width) element.width = config.width
if(config.height) element.height = config.height
if(config.x) element.x = config.x
if(config.y) element.y = config.y
if(config.fillColor) element.fillColor = config.fillColor
if(config.radius) element.radius = config.radius
return element
}
createAnimation(imageKey, length, runTime, endCallback?, order?:boolean) {
let element = new MyAnimation()
element.id = "ANI-" + imageKey + "-" + Math.floor(Math.random()*10000)
if(order){
for (let index = length; index > 0; index--) {
element.addFrameByImg(this.images.get(`${imageKey} (${index})`))
}
}else{
for (let index = 0; index < length; index++) {
element.addFrameByImg(this.images.get(`${imageKey} (${index + 1})`))
}
}
element.delayPerUnit = (runTime / length) / 1000
if (element.delayPerUnit > 1) {
element.delayPerUnit = 1
} else if (element.delayPerUnit < 0.01) {
element.delayPerUnit = 0.01;
}
element.playEndFunc = () => {
endCallback && endCallback()
}
return element
}
attachProperties(cartoonElement){
// cartoonElement.updateBoundingBox = ()=>{
// cartoonElement.boundingBox = cartoonElement.ref.getBoundingBox()
// }
// cartoonElement.boundingBox = cartoonElement.ref.getBoundingBox()
}
getCartoonElementRef = (key) => {
if (this.cartoonElementsBuffer[key]) {
return this.cartoonElementsBuffer[key].ref;
} else {
return undefined
}
}
getCartoonElement = (key) => {
return this.cartoonElementsBuffer[key]
}
getCartoonElementsRef = (keys) => {
let allElelemts = []
keys.forEach(id => {
if (this.cartoonElementsBuffer[id]) {
allElelemts.push(this.cartoonElementsBuffer[id].ref)
}
});
return allElelemts
}
getCartoonElements = (keys) => {
let allElelemts = []
keys.forEach(id => {
if (this.cartoonElementsBuffer[id]) {
allElelemts.push(this.cartoonElementsBuffer[id])
}
});
return allElelemts
}
getAllCartoonElement = () => {
return this.cartoonElementsBuffer
}
setCartoonElementPosition = (key, posi) => {
this.cartoonElementsBuffer[key].ref.x = posi.x
this.cartoonElementsBuffer[key].ref.y = posi.y
this.cartoonElementsBuffer[key].x = posi.x
this.cartoonElementsBuffer[key].y = posi.y
}
setCartoonElementPositionX = (key, x) => {
this.cartoonElementsBuffer[key].ref.x = x
this.cartoonElementsBuffer[key].x = x
}
setCartoonElementRelativePositionX = (key, x) => {
this.cartoonElementsBuffer[key].relativeX = x
}
setCartoonElementPositionY = (key, y) => {
this.cartoonElementsBuffer[key].ref.y = y
this.cartoonElementsBuffer[key].y = y
}
setCartoonElementRelativePositionY = (key, y) => {
this.cartoonElementsBuffer[key].relativeY = y
}
getCartoonElementPosition = (key) => {
return {
x: this.cartoonElementsBuffer[key].x,
y: this.cartoonElementsBuffer[key].y
}
}
getCartoonElementRelativePosition = (key) => {
return {
x: this.cartoonElementsBuffer[key].relativeX,
y: this.cartoonElementsBuffer[key].relativeY
}
}
saveSize(key){
this.cartoonElementsBuffer[key].initX = this.cartoonElementsBuffer[key].ref.x
this.cartoonElementsBuffer[key].initY = this.cartoonElementsBuffer[key].ref.y
this.cartoonElementsBuffer[key].initScaleX = this.cartoonElementsBuffer[key].ref.scaleX
this.cartoonElementsBuffer[key].initScaleY = this.cartoonElementsBuffer[key].ref.scaleX
this.cartoonElementsBuffer[key].ref.initX = this.cartoonElementsBuffer[key].ref.x
this.cartoonElementsBuffer[key].ref.initY = this.cartoonElementsBuffer[key].ref.y
this.cartoonElementsBuffer[key].ref.initScaleX = this.cartoonElementsBuffer[key].ref.scaleX
this.cartoonElementsBuffer[key].ref.initScaleY = this.cartoonElementsBuffer[key].ref.scaleX
}
resetAll = () => {
this.cartoonElementsBuffer = {}
}
}
\ No newline at end of file
import TWEEN from "@tweenjs/tween.js";
import TWEEN from '@tweenjs/tween.js'; import simplexNoise from "../../assets/play/libs/simplex-noise/simplex-noise.min.js"
import { del } from "selenium-webdriver/http";
interface AirWindow extends Window { import construct = Reflect.construct;
air: any;
curCtx: any;
}
declare let window: AirWindow;
class Sprite { class Sprite {
x = 0; x = 0;
y = 0; y = 0;
color = ''; color = "";
radius = 0; radius = 0;
alive = false; alive = false;
margin = 0; margin = 0;
angle = 0; angle = 0;
ctx; ctx;
id;
constructor(ctx = null) { constructor(ctx = null) {
if (!ctx) { if (!ctx) {
this.ctx = window.curCtx; this.ctx = window["curCtx"];
} else { } else {
this.ctx = ctx; this.ctx = ctx;
} }
...@@ -27,18 +23,10 @@ class Sprite { ...@@ -27,18 +23,10 @@ class Sprite {
update($event) { update($event) {
this.draw(); this.draw();
} }
draw() { draw() { }
}
} }
export class MySprite extends Sprite { export class MySprite extends Sprite {
_width = 0; _width = 0;
_height = 0; _height = 0;
_anchorX = 0; _anchorX = 0;
...@@ -53,14 +41,6 @@ export class MySprite extends Sprite { ...@@ -53,14 +41,6 @@ export class MySprite extends Sprite {
skewX = 0; skewX = 0;
skewY = 0; skewY = 0;
_shadowFlag = false;
_shadowColor;
_shadowOffsetX = 0;
_shadowOffsetY = 0;
_shadowBlur = 5;
_radius = 0;
children = [this]; children = [this];
childDepandVisible = true; childDepandVisible = true;
...@@ -69,146 +49,69 @@ export class MySprite extends Sprite { ...@@ -69,146 +49,69 @@ export class MySprite extends Sprite {
img; img;
_z = 0; _z = 0;
init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) { init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) {
if (imgObj) { if (imgObj) {
this.img = imgObj; this.img = imgObj;
this.width = this.img.width; this.width = this.img.width;
this.height = this.img.height; this.height = this.img.height;
} }
this.anchorX = anchorX; this.anchorX = anchorX;
this.anchorY = anchorY; this.anchorY = anchorY;
} }
setShadow(offX, offY, blur, color = 'rgba(0, 0, 0, 0.3)') {
this._shadowFlag = true;
this._shadowColor = color;
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
this._shadowBlur = blur;
}
setRadius(r) {
this._radius = r;
}
update($event = null) { update($event = null) {
if (!this.visible && this.childDepandVisible) { if (!this.visible && this.childDepandVisible) {
return; return;
} }
this.draw(); this.draw();
} }
draw() {
draw() {
this.ctx.save(); this.ctx.save();
this.drawInit(); this.drawInit();
this.updateChildren(); this.updateChildren();
this.ctx.restore(); this.ctx.restore();
} }
drawInit() { drawInit() {
this.ctx.translate(this.x, this.y); this.ctx.translate(this.x, this.y);
this.ctx.rotate((this.rotation * Math.PI) / 180);
this.ctx.rotate(this.rotation * Math.PI / 180);
this.ctx.scale(this.scaleX, this.scaleY); this.ctx.scale(this.scaleX, this.scaleY);
this.ctx.globalAlpha = this.alpha; this.ctx.globalAlpha = this.alpha;
this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0); this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0);
if (this._radius) {
const r = this._radius;
const w = this.width;
const h = this.height;
this.ctx.lineTo(-w / 2, h / 2); // 创建水平线
this.ctx.arcTo(-w / 2, -h / 2, -w / 2 + r, -h / 2, r);
this.ctx.arcTo(w / 2, -h / 2, w / 2, -h / 2 + r, r);
this.ctx.arcTo(w / 2, h / 2, w / 2 - r, h / 2, r);
this.ctx.arcTo(-w / 2, h / 2, -w / 2, h / 2 - r, r);
this.ctx.clip();
}
} }
drawSelf() { drawSelf() {
if (this._shadowFlag) {
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
this.ctx.shadowBlur = this._shadowBlur;
this.ctx.shadowColor = this._shadowColor;
} else {
this.ctx.shadowOffsetX = 0;
this.ctx.shadowOffsetY = 0;
this.ctx.shadowBlur = null;
this.ctx.shadowColor = null;
}
if (this.img) { if (this.img) {
this.ctx.drawImage(this.img, this._offX, this._offY); this.ctx.drawImage(this.img, this._offX, this._offY);
} }
} }
updateChildren() { updateChildren() {
if (this.children.length <= 0) {
return;
}
if (this.children.length <= 0) { return; } for (let i = 0; i < this.children.length; i++) {
if (this.children[i] === this) {
for (const child of this.children) {
if (child === this) {
if (this.visible) { if (this.visible) {
this.drawSelf(); this.drawSelf();
} }
} else { } else {
child.update(); this.children[i].update();
} }
} }
} }
load(url, anchorX = 0.5, anchorY = 0.5) { load(url, anchorX = 0.5, anchorY = 0.5) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const img = new Image(); const img = new Image();
img.onload = () => resolve(img); img.onload = () => resolve(img);
img.onerror = reject; img.onerror = reject;
img.src = url; img.src = url;
}).then(img => { }).then(img => {
this.init(img, anchorX, anchorY); this.init(img, anchorX, anchorY);
return img; return img;
}); });
...@@ -225,12 +128,11 @@ export class MySprite extends Sprite { ...@@ -225,12 +128,11 @@ export class MySprite extends Sprite {
return a._z - b._z; return a._z - b._z;
}); });
if (this.childDepandAlpha) { if (this.childDepandAlpha) {
child.alpha = this.alpha; child.alpha = this.alpha;
} }
} }
removeChild(child) { removeChild(child) {
const index = this.children.indexOf(child); const index = this.children.indexOf(child);
if (index !== -1) { if (index !== -1) {
...@@ -241,22 +143,62 @@ export class MySprite extends Sprite { ...@@ -241,22 +143,62 @@ export class MySprite extends Sprite {
removeChildren() { removeChildren() {
for (let i = 0; i < this.children.length; i++) { for (let i = 0; i < this.children.length; i++) {
if (this.children[i]) { if (this.children[i]) {
if (this.children[i] !== this) { if (this.children[i] != this) {
this.children.splice(i, 1); this.children.splice(i, 1);
i --; i--;
} }
} }
} }
} }
_changeChildAlpha(alpha) { _changeChildAlpha(alpha) {
for (const child of this.children) { for (let i = 0; i < this.children.length; i++) {
if (child !== this) { if (this.children[i] != this) {
child.alpha = alpha; this.children[i].alpha = alpha;
} }
} }
} }
refreshAnchorOff() {
this._offX = -this._width * this.anchorX;
this._offY = -this._height * this.anchorY;
}
setScaleXY(value) {
this.scaleX = this.scaleY = value;
}
getBoundingBox() {
const getParentData = item => {
let px = item.x;
let py = item.y;
let sx = item.scaleX;
let sy = item.scaleY;
const parent = item.parent;
if (parent) {
const obj = getParentData(parent);
const _x = obj.px;
const _y = obj.py;
const _sx = obj.sx;
const _sy = obj.sy;
px = _x + item.x * _sx;
py = _y + item.y * _sy;
sx *= _sx;
sy *= _sy;
}
return { px, py, sx, sy };
};
const data = getParentData(this);
const x = data.px + this._offX * Math.abs(data.sx);
const y = data.py + this._offY * Math.abs(data.sy);
const width = this.width * Math.abs(data.sx);
const height = this.height * Math.abs(data.sy);
return { x, y, width, height };
}
set alpha(v) { set alpha(v) {
this._alpha = v; this._alpha = v;
if (this.childDepandAlpha) { if (this.childDepandAlpha) {
...@@ -294,94 +236,83 @@ export class MySprite extends Sprite { ...@@ -294,94 +236,83 @@ export class MySprite extends Sprite {
get anchorY() { get anchorY() {
return this._anchorY; return this._anchorY;
} }
refreshAnchorOff() { }
this._offX = -this._width * this.anchorX;
this._offY = -this._height * this.anchorY;
}
setScaleXY(value) {
this.scaleX = this.scaleY = value;
}
getBoundingBox() {
const getParentData = (item) => {
let px = item.x;
let py = item.y;
let sx = item.scaleX;
let sy = item.scaleY;
const parent = item.parent;
if (parent) {
const obj = getParentData(parent);
const _x = obj.px;
const _y = obj.py;
const _sx = obj.sx;
const _sy = obj.sy;
px = _x + item.x * _sx;
py = _y + item.y * _sy;
sx *= _sx;
sy *= _sy;
export class waterWave extends MySprite {
bottole_r = 100;
bottole_x0 = 100;
bottole_y0 = 100;
simplex = new simplexNoise()
amp = 10; //波浪幅度 可以通过函数传递参数更改不同的幅度
count = 80;
speedY = 0;
speedX = 0;
height = this.bottole_r
water_color = "red"
per = 1.5
_runTimeCtl = new Date().getTime()
draw_self(color, comp, height) {
this.ctx.beginPath();
let r = this.bottole_r
let a = this.bottole_x0 // this.bottole_r*2
let b = this.bottole_y0 // this.bottole_r*2
for (var i = 0; i <= this.count; i++) {
this.speedX += 0.05;
var x = a - r + i * (r * 2 / this.count);
var y = b + r - height + this.simplex.noise2D(this.speedX, this.speedY) * this.amp;
if (x > (a + r)) {
x = a + r
}
if (x < (a - r)) {
x = a - r
} }
return {px, py, sx, sy}; let c_y1 = Math.sqrt(r * r - (x - a) * (x - a)) + b
}; let c_y2 = -Math.sqrt(r * r - (x - a) * (x - a)) + b
if (y > c_y1) {
y = c_y1
const data = getParentData(this); }
if (y < c_y2) {
y = c_y2
const x = data.px + this._offX * Math.abs(data.sx); }
const y = data.py + this._offY * Math.abs(data.sy); this.ctx[i === 0 ? "moveTo" : "lineTo"](x, y);
const width = this.width * Math.abs(data.sx); }
const height = this.height * Math.abs(data.sy); this.ctx.arc(a, b, r, 0, Math.PI);
this.ctx.closePath();
// const x = this.x + this._offX * Math.abs(this.scaleX); this.ctx.fillStyle = color;
// const y = this.y + this._offY * Math.abs(this.scaleY); this.ctx.fill();
// const width = this.width * Math.abs(this.scaleX);
// const height = this.height * Math.abs(this.scaleY);
return {x, y, width, height};
} }
drawSelf() {
super.drawSelf();
this.speedX = 0;
if (new Date().getTime() - this._runTimeCtl > 10) {
this.speedY += 0.02; //每次渲染需要更新波峰波谷值
}
this._runTimeCtl = new Date().getTime()
this.draw_self(this.water_color, "screen", this.height);
}
} }
export class ColorSpr extends MySprite { export class ColorSpr extends MySprite {
r = 0; r = 0;
g = 0; g = 0;
b = 0; b = 0;
createGSCanvas() { createGSCanvas() {
if (!this.img) { if (!this.img) {
return; return;
} }
const rect = this.getBoundingBox(); const rect = this.getBoundingBox();
if (rect.width <= 1 || rect.height <= 1) { if (rect.width <= 1 || rect.height <= 1) {
return; return;
} }
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height); const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for ( let i = 0; i < c.height; i++) { for (let i = 0; i < c.height; i++) {
for ( let j = 0; j < c.width; j++) { for (let j = 0; j < c.width; j++) {
const x = i * 4 * c.width + j * 4;
const x = (i * 4) * c.width + ( j * 4 );
const r = c.data[x]; const r = c.data[x];
const g = c.data[x + 1]; const g = c.data[x + 1];
const b = c.data[x + 2]; const b = c.data[x + 2];
...@@ -390,88 +321,61 @@ export class ColorSpr extends MySprite { ...@@ -390,88 +321,61 @@ export class ColorSpr extends MySprite {
c.data[x + 1] = this.g; c.data[x + 1] = this.g;
c.data[x + 2] = this.b; c.data[x + 2] = this.b;
// c.data[x] = c.data[x + 1] = c.data[x + 2] = (r + g + b) / 3 ;
// // c.data[x + 3] = 255;
} }
} }
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height); this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.createGSCanvas(); this.createGSCanvas();
} }
} }
export class GrayscaleSpr extends MySprite { export class GrayscaleSpr extends MySprite {
grayScale = 120; grayScale = 120;
createGSCanvas() { createGSCanvas() {
if (!this.img) { if (!this.img) {
return; return;
} }
const rect = this.getBoundingBox(); const rect = this.getBoundingBox();
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height); const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for ( let i = 0; i < c.height; i++) { for (let i = 0; i < c.height; i++) {
for ( let j = 0; j < c.width; j++) { for (let j = 0; j < c.width; j++) {
const x = i * 4 * c.width + j * 4;
const x = (i * 4) * c.width + ( j * 4 );
const r = c.data[x]; const r = c.data[x];
const g = c.data[x + 1]; const g = c.data[x + 1];
const b = c.data[x + 2]; const b = c.data[x + 2];
// const a = c.data[x + 3];
c.data[x] = c.data[x + 1] = c.data[x + 2] = this.grayScale; // (r + g + b) / 3; c.data[x] = c.data[x + 1] = c.data[x + 2] = this.grayScale; // (r + g + b) / 3;
// c.data[x + 3] = 255;
} }
} }
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height); this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.createGSCanvas(); this.createGSCanvas();
} }
} }
export class BitMapLabel extends MySprite { export class BitMapLabel extends MySprite {
labelArr; labelArr;
baseUrl; baseUrl;
setText(data, text) { setText(data, text) {
this.labelArr = []; this.labelArr = [];
const labelArr = []; const labelArr = [];
const tmpArr = text.split(''); const tmpArr = text.split("");
let totalW = 0; let totalW = 0;
let h = 0; let h = 0;
for (const tmp of tmpArr) { for (let i = 0; i < tmpArr.length; i++) {
const label = new MySprite(this.ctx); const label = new MySprite(this.ctx);
label.init(data[tmp], 0); label.init(data[tmpArr[i]], 0);
this.addChild(label); this.addChild(label);
labelArr.push(label); labelArr.push(label);
...@@ -479,47 +383,44 @@ export class BitMapLabel extends MySprite { ...@@ -479,47 +383,44 @@ export class BitMapLabel extends MySprite {
h = label.height; h = label.height;
} }
this.width = totalW; this.width = totalW;
this.height = h; this.height = h;
let offX = -totalW / 2; let offX = -totalW / 2;
for (const label of labelArr) { for (let i = 0; i < labelArr.length; i++) {
label.x = offX; labelArr[i].x = offX;
offX += label.width; offX += labelArr[i].width;
} }
this.labelArr = labelArr; this.labelArr = labelArr;
} }
} }
export class Label extends MySprite { export class Label extends MySprite {
text: String;
text: string;
// fontSize:String = '40px'; // fontSize:String = '40px';
fontName = 'Verdana'; fontName: String = "Verdana";
textAlign = 'left'; textAlign: String = "left";
fontSize = 40; fontSize = 40;
fontColor = '#000000'; fontColor = "#000000";
fontWeight = 900; fontWeight = 900;
_maxWidth; maxWidth;
outline = 0; outline = 0;
outlineColor = '#ffffff'; outlineColor = "#ffffff";
// _shadowFlag = false; maxSingalLineWidth = 0;
// _shadowColor; baseY = 0
// _shadowOffsetX; warpLineHeight = 0;
// _shadowOffsetY; _shadowFlag = false;
// _shadowBlur; _shadowColor;
_shadowOffsetX;
_shadowOffsetY;
_shadowBlur;
_outlineFlag = false; _outlineFlag = false;
_outLineWidth; _outLineWidth;
_outLineColor; _outLineColor;
_warpLineY = 0;
constructor(ctx = null) { constructor(ctx = null) {
super(ctx); super(ctx);
...@@ -527,25 +428,47 @@ export class Label extends MySprite { ...@@ -527,25 +428,47 @@ export class Label extends MySprite {
} }
refreshSize() { refreshSize() {
this.ctx.save(); this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
this._width = this.ctx.measureText(this.text).width; this._width = this.ctx.measureText(this.text).width;
this._height = this.fontSize;
this.refreshAnchorOff();
let height = this.fontSize
if (this.maxSingalLineWidth !== 0) {
var words = this.text.split(' ');
var line = '';
let index = 0;
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = this.ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > this.maxSingalLineWidth && n > 0) {
// this.ctx.fillText(line, 0, this._warpLineY);
line = words[n] + ' ';
// this._warpLineY += this.fontSize;
index++
console.log(index)
height += this.fontSize;
}else {
line = testLine;
}
}
this._height = height;
}else{
this.height = this.fontSize;
}
this.refreshAnchorOff();
this.ctx.restore(); this.ctx.restore();
} }
setMaxSize(w) { setMaxSize(w) {
this.maxWidth = w;
this._maxWidth = w;
this.refreshSize(); this.refreshSize();
if (this.width >= w) { if (this.width >= w) {
this.scaleX *= w / this.width; this.scaleX *= w / this.width;
...@@ -554,7 +477,6 @@ export class Label extends MySprite { ...@@ -554,7 +477,6 @@ export class Label extends MySprite {
} }
show(callBack = null) { show(callBack = null) {
this.visible = true; this.visible = true;
if (this.alpha >= 1) { if (this.alpha >= 1) {
...@@ -564,7 +486,7 @@ export class Label extends MySprite { ...@@ -564,7 +486,7 @@ export class Label extends MySprite {
const tween = new TWEEN.Tween(this) const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800) .to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -572,47 +494,41 @@ export class Label extends MySprite { ...@@ -572,47 +494,41 @@ export class Label extends MySprite {
.start(); // Start the tween immediately. .start(); // Start the tween immediately.
} }
// setShadow(offX = 0, offY = 2, blur = 2, color = 'rgba(0, 0, 0, 0.2)') { setShadow(offX = 2, offY = 2, blur = 2, color = "rgba(0, 0, 0, 0.2)") {
// this._shadowFlag = true;
// this._shadowFlag = true; this._shadowColor = color;
// this._shadowColor = color; // 将阴影向右移动15px,向上移动10px
// // 将阴影向右移动15px,向上移动10px this._shadowOffsetX = offX;
// this._shadowOffsetX = 5; this._shadowOffsetY = offY;
// this._shadowOffsetY = 5; // 轻微模糊阴影
// // 轻微模糊阴影 this._shadowBlur = blur;
// this._shadowBlur = 5; }
// }
setOutline(width = 5, color = '#ffffff') {
setOutline(width = 5, color = "#ffffff") {
this._outlineFlag = true; this._outlineFlag = true;
this._outLineWidth = width; this._outLineWidth = width;
this._outLineColor = color; this._outLineColor = color;
} }
drawText() { drawText() {
// console.log('in drawText', this.text); // console.log('in drawText', this.text);
if (!this.text) { return; } if (!this.text) {
return;
}
// if (this._shadowFlag) {
//
// this.ctx.shadowColor = this._shadowColor;
// // 将阴影向右移动15px,向上移动10px
// this.ctx.shadowOffsetX = this._shadowOffsetX;
// this.ctx.shadowOffsetY = this._shadowOffsetY;
// // 轻微模糊阴影
// this.ctx.shadowBlur = this._shadowBlur;
// }
if (this._shadowFlag) {
this.ctx.shadowColor = this._shadowColor;
// 将阴影向右移动15px,向上移动10px
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
// 轻微模糊阴影
this.ctx.shadowBlur = this._shadowBlur;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
if (this._outlineFlag) { if (this._outlineFlag) {
...@@ -623,61 +539,152 @@ export class Label extends MySprite { ...@@ -623,61 +539,152 @@ export class Label extends MySprite {
this.ctx.fillStyle = this.fontColor; this.ctx.fillStyle = this.fontColor;
if (this.outline > 0) { if (this.outline > 0) {
this.ctx.lineWidth = this.outline; this.ctx.lineWidth = this.outline;
this.ctx.strokeStyle = this.outlineColor; this.ctx.strokeStyle = this.outlineColor;
this.ctx.strokeText(this.text, 0, 0); this.ctx.strokeText(this.text, 0, 0);
}
// 当maxSingalLineWidth不为0时,对数据进行换行处理
if (this.maxSingalLineWidth !== 0) {
var words = this.text.split(' ');
var line = '';
this._warpLineY = 0;
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = this.ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > this.maxSingalLineWidth && n > 0) {
this.ctx.fillText(line, 0, this._warpLineY);
line = words[n] + ' ';
this._warpLineY += this.fontSize;
}
else {
line = testLine;
}
}
this.y = this.baseY // + this._warpLineY
this.ctx.fillText(line, 0, this._warpLineY);
} else {
this.ctx.fillText(this.text, 0, 0);
} }
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class ShapeRectNew extends MySprite {
radius = 0;
fillColor = '#ffffff';
strokeColor = '#000000';
fill = true;
stroke = false;
lineWidth = 1;
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
drawShape() {
const ctx = this.ctx;
const width = this.width;
const height = this.height;
const radius = this.radius;
ctx.save();
ctx.beginPath(0);
// 从右下角顺时针绘制,弧度从0到1/2PI
ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
// 矩形下边线
ctx.lineTo(radius, height);
// 左下角圆弧,弧度从1/2PI到PI
ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
// 矩形左边线
ctx.lineTo(0, radius);
// 左上角圆弧,弧度从PI到3/2PI
ctx.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
// 上边线
ctx.lineTo(width - radius, 0);
// 右上角圆弧
ctx.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
this.ctx.fillText(this.text, 0, 0); // 右边线
ctx.lineTo(width, height - radius);
ctx.closePath();
if (this.fill) {
ctx.fillStyle = this.fillColor;
ctx.fill();
}
if (this.stroke) {
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.strokeColor;
ctx.stroke();
}
ctx.restore();
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawText(); this.drawShape();
} }
} }
export class RichTextOld extends Label { export class RichTextOld extends Label {
textArr = []; textArr = [];
fontSize = 40; fontSize = 40;
setText(text: string, words) { setText(text: string, words) {
let newText = text; let newText = text;
for (const word of words) { for (let i = 0; i < words.length; i++) {
const word = words[i];
const re = new RegExp(word, 'g'); const re = new RegExp(word, "g");
newText = newText.replace( re, `#${word}#`); newText = newText.replace(re, `#${word}#`);
// newText = newText.replace(word, `#${word}#`); // newText = newText.replace(word, `#${word}#`);
} }
this.textArr = newText.split('#'); this.textArr = newText.split("#");
this.text = newText; this.text = newText;
// this.setSize(); // this.setSize();
} }
refreshSize() { refreshSize() {
this.ctx.save(); this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
let curX = 0; let curX = 0;
for (const text of this.textArr) { for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(text).width; const w = this.ctx.measureText(this.textArr[i]).width;
curX += w; curX += w;
} }
...@@ -686,12 +693,9 @@ export class RichTextOld extends Label { ...@@ -686,12 +693,9 @@ export class RichTextOld extends Label {
this.refreshAnchorOff(); this.refreshAnchorOff();
this.ctx.restore(); this.ctx.restore();
} }
show(callBack = null) { show(callBack = null) {
// console.log(' in show '); // console.log(' in show ');
this.visible = true; this.visible = true;
// this.alpha = 0; // this.alpha = 0;
...@@ -699,185 +703,119 @@ export class RichTextOld extends Label { ...@@ -699,185 +703,119 @@ export class RichTextOld extends Label {
const tween = new TWEEN.Tween(this) const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800) .to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
}) })
.start(); // Start the tween immediately. .start(); // Start the tween immediately.
} }
drawText() { drawText() {
// console.log('in drawText', this.text); // console.log('in drawText', this.text);
if (!this.text) { return; } if (!this.text) {
return;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = 900; this.ctx.fontWeight = 900;
this.ctx.lineWidth = 5; this.ctx.lineWidth = 5;
this.ctx.strokeStyle = '#ffffff'; this.ctx.strokeStyle = "#ffffff";
// this.ctx.strokeText(this.text, 0, 0); // this.ctx.strokeText(this.text, 0, 0);
this.ctx.fillStyle = '#000000'; this.ctx.fillStyle = "#000000";
// this.ctx.fillText(this.text, 0, 0); // this.ctx.fillText(this.text, 0, 0);
let curX = 0; let curX = 0;
for (let i = 0; i < this.textArr.length; i++) { for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width; const w = this.ctx.measureText(this.textArr[i]).width;
if ((i + 1) % 2 === 0) { if ((i + 1) % 2 == 0) {
this.ctx.fillStyle = '#c8171e'; this.ctx.fillStyle = "#c8171e";
} else { } else {
this.ctx.fillStyle = '#000000'; this.ctx.fillStyle = "#000000";
} }
this.ctx.fillText(this.textArr[i], curX, 0); this.ctx.fillText(this.textArr[i], curX, 0);
curX += w; curX += w;
} }
} }
} }
export class RichText extends Label { export class RichText extends Label {
disH = 30;
constructor(ctx = null) {
disH = 30;
constructor(ctx?: any) {
super(ctx); super(ctx);
// this.dataArr = dataArr; // this.dataArr = dataArr;
} }
drawText() { drawText() {
if (!this.text) { if (!this.text) {
return; return;
} }
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
this.ctx.fillStyle = this.fontColor; this.ctx.fillStyle = this.fontColor;
const selfW = this.width * this.scaleX; const selfW = this.width * this.scaleX;
const chr = this.text.split(" ");
const chr = this.text.split(' '); let temp = "";
let temp = '';
const row = []; const row = [];
const w = selfW - 80; const w = selfW - 80;
const disH = (this.fontSize + this.disH) * this.scaleY; const disH = (this.fontSize + this.disH) * this.scaleY;
for (let a = 0; a < chr.length; a++) {
if (
this.ctx.measureText(temp).width < w &&
for (const c of chr) { this.ctx.measureText(temp + chr[a]).width <= w
if (this.ctx.measureText(temp).width < w && this.ctx.measureText(temp + (c)).width <= w) { ) {
temp += ' ' + c; temp += " " + chr[a];
} else { } else {
row.push(temp); row.push(temp);
temp = ' ' + c; temp = " " + chr[a];
} }
} }
row.push(temp); row.push(temp);
const x = 0; const x = 0;
const y = -row.length * disH / 2; const y = (-row.length * disH) / 2;
// for (let b = 0 ; b < row.length; b++) { // for (let b = 0 ; b < row.length; b++) {
// this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20 // this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
// } // }
if (this._outlineFlag) { if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth; this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor; this.ctx.strokeStyle = this._outLineColor;
for (let b = 0 ; b < row.length; b++) { for (let b = 0; b < row.length; b++) {
this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20 this.ctx.strokeText(row[b], x, y + (b + 1) * disH); // 每行字体y坐标间隔20
} }
// this.ctx.strokeText(this.text, 0, 0); // this.ctx.strokeText(this.text, 0, 0);
} }
// this.ctx.fillStyle = '#ff7600'; // this.ctx.fillStyle = '#ff7600';
for (let b = 0 ; b < row.length; b++) { for (let b = 0; b < row.length; b++) {
this.ctx.fillText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20 this.ctx.fillText(row[b], x, y + (b + 1) * disH); // 每行字体y坐标间隔20
} }
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawText(); this.drawText();
} }
}
export class LineRect extends MySprite {
lineColor = '#ffffff';
lineWidth = 10;
setSize(w, h) {
this.width = w;
this.height = h;
}
drawLine() {
this.ctx.beginPath();
this.ctx.moveTo(this._offX, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY + this.height);
this.ctx.lineTo(this._offX, this._offY + this.height);
this.ctx.closePath();
this.ctx.lineWidth = this.lineWidth;
// this.ctx.fillStyle = "rgb(2,33,42)"; //指定填充颜色
// this.ctx.fill(); //对多边形进行填充
this.ctx.strokeStyle = this.lineColor; // "#ffffff";
this.ctx.stroke();
}
drawSelf() {
super.drawSelf();
this.drawLine();
}
} }
export class ShapeRect extends MySprite { export class ShapeRect extends MySprite {
fillColor = "#FF0000";
fillColor = '#FF0000';
setSize(w, h) { setSize(w, h) {
this.width = w; this.width = w;
...@@ -888,136 +826,71 @@ export class ShapeRect extends MySprite { ...@@ -888,136 +826,71 @@ export class ShapeRect extends MySprite {
} }
drawShape() { drawShape() {
this.ctx.fillStyle = this.fillColor; this.ctx.fillStyle = this.fillColor;
this.ctx.fillRect(this._offX, this._offY, this.width, this.height); this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawShape(); this.drawShape();
} }
} }
export class ShapeCircle extends MySprite { export class ShapeCircle extends MySprite {
fillColor = "#FFFF00";
fillColor = '#FF0000';
radius = 0; radius = 0;
startRadian = 0;
endRadian = 180;
strokeLineWidth = 5;
strokeColor = "#702dee";
drawType = "fill"
counterclockwise = false; // false 逆时针 true 顺时针
shadowColor = "rgba(0,0,0,0)"
shadowOffsetX = 0;
shadowOffsetY = 0;
setRadius(r) { setRadius(r) {
this.anchorX = this.anchorY = 0.5; this.anchorX = this.anchorY = 0.5;
this.radius = r; this.radius = r;
this.width = r * 2; this.width = r * 2;
this.height = r * 2; this.height = r * 2;
} }
drawShape() { drawShape() {
switch (this.drawType) {
this.ctx.beginPath(); case "stroke":
this.ctx.fillStyle = this.fillColor; this.ctx.beginPath();
this.ctx.arc(0, 0, this.radius, 0, angleToRadian(360)); this.ctx.strokeStyle = this.strokeColor;
this.ctx.fill(); this.ctx.lineWidth = this.strokeLineWidth
} this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian, this.counterclockwise);
this.ctx.stroke()
drawSelf() { break;
super.drawSelf(); default:
this.drawShape(); this.ctx.beginPath();
} this.ctx.fillStyle = this.fillColor;
} this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian);
this.ctx.shadowColor = this.shadowColor
export class ShapeRectNew extends MySprite { this.ctx.shadowOffsetX = this.shadowOffsetX
this.ctx.shadowOffsetY = this.shadowOffsetY
this.ctx.fill();
radius = 0; break;
fillColor = '#ffffff';
strokeColor = '#000000';
fill = true;
stroke = false;
lineWidth = 1;
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
drawShape() {
const ctx = this.ctx;
const width = this.width;
const height = this.height;
const radius = this.radius;
ctx.save();
ctx.beginPath(0);
// 从右下角顺时针绘制,弧度从0到1/2PI
ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
// 矩形下边线
ctx.lineTo(radius, height);
// 左下角圆弧,弧度从1/2PI到PI
ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
// 矩形左边线
ctx.lineTo(0, radius);
// 左上角圆弧,弧度从PI到3/2PI
ctx.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
// 上边线
ctx.lineTo(width - radius, 0);
// 右上角圆弧
ctx.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
// 右边线
ctx.lineTo(width, height - radius);
ctx.closePath();
if (this.fill) {
ctx.fillStyle = this.fillColor;
ctx.fill();
}
if (this.stroke) {
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.strokeColor;
ctx.stroke();
} }
ctx.restore();
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawShape(); this.drawShape();
} }
} }
export class MyAnimation extends MySprite {
export class MyAnimation extends MySprite {
frameArr = []; frameArr = [];
frameIndex = 0; frameIndex = 0;
playFlag = false; playFlag = false;
lastDateTime; lastDateTime;
curDelay = 0; curDelay = 0;
loop = false; loop = false;
playEndFunc; playEndFunc;
delayPerUnit = 1; delayPerUnit = 1;
...@@ -1026,7 +899,6 @@ export class MyAnimation extends MySprite { ...@@ -1026,7 +899,6 @@ export class MyAnimation extends MySprite {
reverseFlag = false; reverseFlag = false;
addFrameByImg(img) { addFrameByImg(img) {
const spr = new MySprite(this.ctx); const spr = new MySprite(this.ctx);
spr.init(img); spr.init(img);
this._refreshSize(img); this._refreshSize(img);
...@@ -1040,10 +912,8 @@ export class MyAnimation extends MySprite { ...@@ -1040,10 +912,8 @@ export class MyAnimation extends MySprite {
} }
addFrameByUrl(url) { addFrameByUrl(url) {
const spr = new MySprite(this.ctx); const spr = new MySprite(this.ctx);
spr.load(url).then(img => { spr.load(url).then(img => {
this._refreshSize(img); this._refreshSize(img);
}); });
spr.visible = false; spr.visible = false;
...@@ -1054,18 +924,15 @@ export class MyAnimation extends MySprite { ...@@ -1054,18 +924,15 @@ export class MyAnimation extends MySprite {
this.frameArr[this.frameIndex].visible = true; this.frameArr[this.frameIndex].visible = true;
} }
_refreshSize(img: any) { _refreshSize(img) {
if (this.width < img["width"]) {
if (this.width < img.width) { this.width = img["width"];
this.width = img.width;
} }
if (this.height < img.height) { if (this.height < img["height"]) {
this.height = img.height; this.height = img["height"];
} }
} }
play() { play() {
this.playFlag = true; this.playFlag = true;
this.lastDateTime = new Date().getTime(); this.lastDateTime = new Date().getTime();
...@@ -1075,13 +942,11 @@ export class MyAnimation extends MySprite { ...@@ -1075,13 +942,11 @@ export class MyAnimation extends MySprite {
this.playFlag = false; this.playFlag = false;
} }
replay() { replay() {
this.restartFlag = true; this.restartFlag = true;
this.play(); this.play();
} }
reverse() { reverse() {
this.reverseFlag = !this.reverseFlag; this.reverseFlag = !this.reverseFlag;
this.frameArr.reverse(); this.frameArr.reverse();
...@@ -1089,20 +954,18 @@ export class MyAnimation extends MySprite { ...@@ -1089,20 +954,18 @@ export class MyAnimation extends MySprite {
} }
showAllFrame() { showAllFrame() {
for (const frame of this.frameArr ) { for (let i = 0; i < this.frameArr.length; i++) {
frame.alpha = 1; this.frameArr[i].alpha = 1;
} }
} }
hideAllFrame() { hideAllFrame() {
for (const frame of this.frameArr) { for (let i = 0; i < this.frameArr.length; i++) {
frame.alpha = 0; this.frameArr[i].alpha = 0;
} }
} }
playEnd() { playEnd() {
this.playFlag = false; this.playFlag = false;
this.curDelay = 0; this.curDelay = 0;
...@@ -1119,7 +982,7 @@ export class MyAnimation extends MySprite { ...@@ -1119,7 +982,7 @@ export class MyAnimation extends MySprite {
this.frameArr[this.frameIndex].visible = false; this.frameArr[this.frameIndex].visible = false;
} }
this.frameIndex ++; this.frameIndex++;
if (this.frameIndex >= this.frameArr.length) { if (this.frameIndex >= this.frameArr.length) {
if (this.loop) { if (this.loop) {
this.frameIndex = 0; this.frameIndex = 0;
...@@ -1127,21 +990,16 @@ export class MyAnimation extends MySprite { ...@@ -1127,21 +990,16 @@ export class MyAnimation extends MySprite {
this.restartFlag = false; this.restartFlag = false;
this.frameIndex = 0; this.frameIndex = 0;
} else { } else {
this.frameIndex -- ; this.frameIndex--;
this.playEnd(); this.playEnd();
return; return;
} }
} }
this.frameArr[this.frameIndex].visible = true; this.frameArr[this.frameIndex].visible = true;
} }
_updateDelay(delay) { _updateDelay(delay) {
this.curDelay += delay; this.curDelay += delay;
if (this.curDelay < this.delayPerUnit) { if (this.curDelay < this.delayPerUnit) {
return; return;
...@@ -1151,7 +1009,9 @@ export class MyAnimation extends MySprite { ...@@ -1151,7 +1009,9 @@ export class MyAnimation extends MySprite {
} }
_updateLastDate() { _updateLastDate() {
if (!this.playFlag) { return; } if (!this.playFlag) {
return;
}
let delay = 0; let delay = 0;
if (this.lastDateTime) { if (this.lastDateTime) {
...@@ -1165,18 +1025,18 @@ export class MyAnimation extends MySprite { ...@@ -1165,18 +1025,18 @@ export class MyAnimation extends MySprite {
super.update($event); super.update($event);
this._updateLastDate(); this._updateLastDate();
} }
} }
// --------=========== util func =============------------- // --------=========== util func =============-------------
export function tweenChange(
export function tweenChange(item, obj, time = 0.8, callBack = null, easing = null, update = null) { item,
obj,
time = 0.8,
callBack = null,
easing = null,
update = null
) {
const tween = new TWEEN.Tween(item).to(obj, time * 1000); const tween = new TWEEN.Tween(item).to(obj, time * 1000);
if (callBack) { if (callBack) {
...@@ -1188,7 +1048,7 @@ export function tweenChange(item, obj, time = 0.8, callBack = null, easing = nul ...@@ -1188,7 +1048,7 @@ export function tweenChange(item, obj, time = 0.8, callBack = null, easing = nul
tween.easing(easing); tween.easing(easing);
} }
if (update) { if (update) {
tween.onUpdate( (a, b) => { tween.onUpdate((a, b) => {
update(a, b); update(a, b);
}); });
} }
...@@ -1197,11 +1057,13 @@ export function tweenChange(item, obj, time = 0.8, callBack = null, easing = nul ...@@ -1197,11 +1057,13 @@ export function tweenChange(item, obj, time = 0.8, callBack = null, easing = nul
return tween; return tween;
} }
export function rotateItem(
item,
rotation,
export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = null) { time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000); const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000);
if (callBack) { if (callBack) {
...@@ -1216,11 +1078,17 @@ export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = ...@@ -1216,11 +1078,17 @@ export function rotateItem(item, rotation, time = 0.8, callBack = null, easing =
tween.start(); tween.start();
} }
export function scaleItem(
item,
export function scaleItem(item, scale, time = 0.8, callBack = null, easing = null) { scale,
time = 0.8,
const tween = new TWEEN.Tween(item).to({ scaleX: scale, scaleY: scale}, time * 1000); callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to(
{ scaleX: scale, scaleY: scale },
time * 1000
);
if (callBack) { if (callBack) {
tween.onComplete(() => { tween.onComplete(() => {
...@@ -1235,10 +1103,15 @@ export function scaleItem(item, scale, time = 0.8, callBack = null, easing = nul ...@@ -1235,10 +1103,15 @@ export function scaleItem(item, scale, time = 0.8, callBack = null, easing = nul
return tween; return tween;
} }
export function moveItem(
export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) { item,
x,
const tween = new TWEEN.Tween(item).to({ x, y}, time * 1000); y,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to({ x, y }, time * 1000);
if (callBack) { if (callBack) {
tween.onComplete(() => { tween.onComplete(() => {
...@@ -1254,36 +1127,26 @@ export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) ...@@ -1254,36 +1127,26 @@ export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null)
return tween; return tween;
} }
export function endShow(item, s = 1) { export function endShow(item, s = 1) {
item.scaleX = item.scaleY = 0; item.scaleX = item.scaleY = 0;
item.alpha = 0; item.alpha = 0;
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({ alpha: 1, scaleX: s, scaleY: s }, 800) .to({ alpha: 1, scaleX: s, scaleY: s }, 800)
.easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth. .easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () { })
})
.start(); .start();
} }
export function hideItem(item, time = 0.8, callBack = null, easing = null) { export function hideItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha == 0) {
if (item.alpha === 0) {
return; return;
} }
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha: 0}, time * 1000) .to({ alpha: 0 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1296,10 +1159,8 @@ export function hideItem(item, time = 0.8, callBack = null, easing = null) { ...@@ -1296,10 +1159,8 @@ export function hideItem(item, time = 0.8, callBack = null, easing = null) {
tween.start(); tween.start();
} }
export function showItem(item, time = 0.8, callBack = null, easing = null) { export function showItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha == 1) {
if (item.alpha === 1) {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1308,9 +1169,9 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) { ...@@ -1308,9 +1169,9 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) {
item.visible = true; item.visible = true;
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha: 1}, time * 1000) .to({ alpha: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1323,14 +1184,17 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) { ...@@ -1323,14 +1184,17 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) {
tween.start(); tween.start();
} }
export function alphaItem(
export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = null) { item,
alpha,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha}, time * 1000) .to({ alpha: alpha }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1343,14 +1207,11 @@ export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = nul ...@@ -1343,14 +1207,11 @@ export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = nul
tween.start(); tween.start();
} }
export function showStar(item, time = 0.8, callBack = null, easing = null) { export function showStar(item, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha: 1, scale: 1}, time * 1000) .to({ alpha: 1, scale: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1363,97 +1224,103 @@ export function showStar(item, time = 0.8, callBack = null, easing = null) { ...@@ -1363,97 +1224,103 @@ export function showStar(item, time = 0.8, callBack = null, easing = null) {
tween.start(); tween.start();
} }
export function randomSortByArr(arr) { export function randomSortByArr(arr) {
const newArr = []; const newArr = [];
const tmpArr = arr.concat(); const tmpArr = arr.concat();
while (tmpArr.length > 0) { while (tmpArr.length > 0) {
const randomIndex = Math.floor( tmpArr.length * Math.random() ); const randomIndex = Math.floor(tmpArr.length * Math.random());
newArr.push(tmpArr[randomIndex]); newArr.push(tmpArr[randomIndex]);
tmpArr.splice(randomIndex, 1); tmpArr.splice(randomIndex, 1);
} }
return newArr; return newArr;
} }
export function radianToAngle(radian) { export function radianToAngle(radian) {
return radian * 180 / Math.PI; return (radian * 180) / Math.PI;
// 角度 = 弧度 * 180 / Math.PI; // 角度 = 弧度 * 180 / Math.PI;
} }
export function angleToRadian(angle) { export function angleToRadian(angle) {
return angle * Math.PI / 180; return (angle * Math.PI) / 180;
// 弧度= 角度 * Math.PI / 180; // 弧度= 角度 * Math.PI / 180;
} }
export function getPosByAngle(angle, len) { export function getPosByAngle(angle, len) {
const radian = (angle * Math.PI) / 180;
const radian = angle * Math.PI / 180;
const x = Math.sin(radian) * len; const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len; const y = Math.cos(radian) * len;
return {x, y}; return { x, y };
} }
export function getAngleByPos(px, py, mx, my) { export function getAngleByPos(px, py, mx, my) {
const x = Math.abs(px - mx); const x = Math.abs(px - mx);
const y = Math.abs(py - my); const y = Math.abs(py - my);
const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
const cos = y / z; const cos = y / z;
const radina = Math.acos(cos); // 用反三角函数求弧度 const radina = Math.acos(cos); // 用反三角函数求弧度
let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度 let angle = Math.floor((180 / (Math.PI / radina)) * 100) / 100; // 将弧度转换成角度
if (mx > px && my > py) {// 鼠标在第四象限 if (mx > px && my > py) {
// 鼠标在第四象限
angle = 180 - angle; angle = 180 - angle;
} }
if (mx === px && my > py) {// 鼠标在y轴负方向上 if (mx === px && my > py) {
// 鼠标在y轴负方向上
angle = 180; angle = 180;
} }
if (mx > px && my === py) {// 鼠标在x轴正方向上 if (mx > px && my === py) {
// 鼠标在x轴正方向上
angle = 90; angle = 90;
} }
if (mx < px && my > py) {// 鼠标在第三象限 if (mx < px && my > py) {
// 鼠标在第三象限
angle = 180 + angle; angle = 180 + angle;
} }
if (mx < px && my === py) {// 鼠标在x轴负方向 if (mx < px && my === py) {
// 鼠标在x轴负方向
angle = 270; angle = 270;
} }
if (mx < px && my < py) {// 鼠标在第二象限 if (mx < px && my < py) {
// 鼠标在第二象限
angle = 360 - angle; angle = 360 - angle;
} }
// console.log('angle: ', angle); // console.log('angle: ', angle);
return angle; return angle;
} }
export function removeItemFromArr(arr, item) { export function removeItemFromArr(arr, item) {
const index = arr.indexOf(item); const index = arr.indexOf(item);
if (index !== -1) { if (index != -1) {
arr.splice(index, 1); arr.splice(index, 1);
} }
} }
export function circleMove(
item,
x0,
y0,
time = 2,
export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = 1, callBack = null, easing = null) { addR = 360,
xPer = 1,
yPer = 1,
callBack = null,
easing = null
) {
const r = getPosDistance(item.x, item.y, x0, y0); const r = getPosDistance(item.x, item.y, x0, y0);
let a = getAngleByPos(item.x, item.y, x0, y0); let a = getAngleByPos(item.x, item.y, x0, y0);
a += 90; a += 90;
const obj = {r, a}; const obj = { r, a };
item._circleAngle = a; item._circleAngle = a;
const targetA = a + addR; const targetA = a + addR;
const tween = new TWEEN.Tween(item).to({_circleAngle: targetA}, time * 1000); const tween = new TWEEN.Tween(item).to(
{ _circleAngle: targetA },
time * 1000
);
if (callBack) { if (callBack) {
tween.onComplete(() => { tween.onComplete(() => {
...@@ -1464,14 +1331,13 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = ...@@ -1464,14 +1331,13 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer =
tween.easing(easing); tween.easing(easing);
} }
tween.onUpdate( (item, progress) => { tween.onUpdate((item, progress) => {
// console.log(item._circleAngle); // console.log(item._circleAngle);
const r = obj.r; const r = obj.r;
const a = item._circleAngle; const a = item._circleAngle;
const x = x0 + r * xPer * Math.cos(a * Math.PI / 180); const x = x0 + r * xPer * Math.cos((a * Math.PI) / 180);
const y = y0 + r * yPer * Math.sin(a * Math.PI / 180); const y = y0 + r * yPer * Math.sin((a * Math.PI) / 180);
item.x = x; item.x = x;
item.y = y; item.y = y;
...@@ -1482,12 +1348,10 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = ...@@ -1482,12 +1348,10 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer =
tween.start(); tween.start();
} }
export function getPosDistance(sx, sy, ex, ey) { export function getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx; const _x = ex - sx;
const _y = ey - sy; const _y = ey - sy;
const len = Math.sqrt( Math.pow(_x, 2) + Math.pow(_y, 2) ); const len = Math.sqrt(Math.pow(_x, 2) + Math.pow(_y, 2));
return len; return len;
} }
...@@ -1502,29 +1366,6 @@ export function delayCall(callback, second) { ...@@ -1502,29 +1366,6 @@ export function delayCall(callback, second) {
.start(); .start();
} }
export function formatTime(fmt, date) {
// "yyyy-MM-dd HH:mm:ss";
const o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); }
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1)
? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return fmt;
}
export function getMinScale(item, maxLen) { export function getMinScale(item, maxLen) {
const sx = maxLen / item.width; const sx = maxLen / item.width;
const sy = maxLen / item.height; const sy = maxLen / item.height;
...@@ -1532,11 +1373,7 @@ export function getMinScale(item, maxLen) { ...@@ -1532,11 +1373,7 @@ export function getMinScale(item, maxLen) {
return minS; return minS;
} }
export function jelly(item, time = 0.7) { export function jelly(item, time = 0.7) {
if (item.jellyTween) { if (item.jellyTween) {
TWEEN.remove(item.jellyTween); TWEEN.remove(item.jellyTween);
} }
...@@ -1552,10 +1389,16 @@ export function jelly(item, time = 0.7) { ...@@ -1552,10 +1389,16 @@ export function jelly(item, time = 0.7) {
return; return;
} }
const data = arr[index]; const data = arr[index];
const t = tweenChange(item, {scaleX: data[0], scaleY: data[1]}, data[2], () => { const t = tweenChange(
index ++; item,
run(); { scaleX: data[0], scaleY: data[1] },
}, TWEEN.Easing.Sinusoidal.InOut); data[2],
() => {
index++;
run();
},
TWEEN.Easing.Sinusoidal.InOut
);
item.jellyTween = t; item.jellyTween = t;
}; };
...@@ -1564,20 +1407,24 @@ export function jelly(item, time = 0.7) { ...@@ -1564,20 +1407,24 @@ export function jelly(item, time = 0.7) {
[baseSX * 0.98, baseSY * 1.02, t * 2], [baseSX * 0.98, baseSY * 1.02, t * 2],
[baseSX * 1.02, baseSY * 0.98, t * 2], [baseSX * 1.02, baseSY * 0.98, t * 2],
[baseSX * 0.99, baseSY * 1.01, t * 2], [baseSX * 0.99, baseSY * 1.01, t * 2],
[baseSX * 1.0, baseSY * 1.0, t * 2], [baseSX * 1.0, baseSY * 1.0, t * 2]
]; ];
run(); run();
} }
/**
* 烟花爆炸效果动画
export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen = 80, showTime = 0.4) { * @param img 颗粒的图片
* @param pos 爆点的坐标
* @param parent 必须传一个父类
for (let i = 0; i < num; i ++) { */
export function showPopParticle(img, pos, parent) {
const num = 20;
const maxLen = 100;
const minLen = 40;
for (let i = 0; i < num; i++) {
const particle = new MySprite(); const particle = new MySprite();
particle.init(img); particle.init(img);
particle.x = pos.x; particle.x = pos.x;
...@@ -1587,8 +1434,8 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen ...@@ -1587,8 +1434,8 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen
const randomR = 360 * Math.random(); const randomR = 360 * Math.random();
particle.rotation = randomR; particle.rotation = randomR;
const randomS = 0.3 + Math.random() * 0.7; const randomS = 0.5 + Math.random() * 0.5;
particle.setScaleXY(randomS * 0.3); particle.setScaleXY(randomS);
const randomX = Math.random() * 20 - 10; const randomX = Math.random() * 20 - 10;
particle.x += randomX; particle.x += randomX;
...@@ -1596,39 +1443,23 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen ...@@ -1596,39 +1443,23 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen
const randomY = Math.random() * 20 - 10; const randomY = Math.random() * 20 - 10;
particle.y += randomY; particle.y += randomY;
const randomL = minLen + Math.random() * (maxLen - minLen); const randomL = minLen + Math.random() * maxLen;
const randomA = 360 * Math.random(); const randomA = 360 * Math.random();
const randomT = getPosByAngle(randomA, randomL); const randomT = getPosByAngle(randomA, randomL);
moveItem(particle, particle.x + randomT.x, particle.y + randomT.y, showTime, () => { moveItem(
particle,
particle.x + randomT.x,
particle.y + randomT.y,
}, TWEEN.Easing.Exponential.Out); 0.4,
() => { },
// scaleItem(particle, 0, 0.6, () => { TWEEN.Easing.Exponential.Out
// );
// });
scaleItem(particle, randomS, 0.6, () => {
}, TWEEN.Easing.Exponential.Out);
setTimeout(() => {
hideItem(particle, 0.4, () => {
}, TWEEN.Easing.Cubic.In);
}, showTime * 0.5 * 1000);
scaleItem(particle, 0, 0.6, () => { });
} }
} }
export function shake(item, time = 0.5, callback = null, rate = 1) { export function shake(item, time = 0.5, callback = null, rate = 1) {
if (item.shakeTween) { if (item.shakeTween) {
return; return;
} }
...@@ -1640,37 +1471,104 @@ export function shake(item, time = 0.5, callback = null, rate = 1) { ...@@ -1640,37 +1471,104 @@ export function shake(item, time = 0.5, callback = null, rate = 1) {
const baseY = item.y; const baseY = item.y;
const easing = TWEEN.Easing.Sinusoidal.InOut; const easing = TWEEN.Easing.Sinusoidal.InOut;
const move4 = () => { const move4 = () => {
moveItem(item, baseX, baseY, time / 4, () => { moveItem(
item.shakeTween = false; item,
if (callback) { baseX,
callback(); baseY,
} time / 4,
}, easing); () => {
item.shakeTween = false;
if (callback) {
callback();
}
},
easing
);
}; };
const move3 = () => { const move3 = () => {
moveItem(item, baseX + offX / 4, baseY + offY / 4, time / 4, () => { moveItem(
move4(); item,
}, easing); baseX + offX / 4,
baseY + offY / 4,
time / 4,
() => {
move4();
},
easing
);
}; };
const move2 = () => { const move2 = () => {
moveItem(item, baseX - offX / 4 * 3, baseY - offY / 4 * 3, time / 4, () => { moveItem(
move3(); item,
}, easing); baseX - (offX / 4) * 3,
baseY - (offY / 4) * 3,
time / 4,
() => {
move3();
},
easing
);
}; };
const move1 = () => { const move1 = () => {
moveItem(item, baseX + offX, baseY + offY, time / 7.5, () => { moveItem(
move2(); item,
}, easing); baseX + offX,
baseY + offY,
time / 8,
() => {
move2();
},
easing
);
}; };
move1(); move1();
} }
// --------------- custom class -------------------- // --------------- custom class --------------------
export function showBlingBling(starImg, rectArea, parent, mapScale = 1, num = 30, disTime = 0.1, showTime = 3) {
const timeId = setInterval(() => {
showBlingStar(starImg, num, rectArea, parent, mapScale);
}, disTime * 1000);
setTimeout(() => {
clearInterval(timeId);
}, showTime * 1000);
}
function showBlingStar(starImg, num, rectArea, parent, mapScale) {
for (let i = 0; i < num; i++) {
const star = new MySprite();
star.init(starImg);
const px = -parent.width / 2 + Math.random() * parent.width;
const py = -parent.height / 2 + Math.random() * parent.height;
star.x = px;
star.y = py;
const randomS = (0.1 + Math.random() * 0.8) * mapScale;
star.setScaleXY(1);
parent.addChild(star);
scaleItem(star, randomS, 0.3, () => {
setTimeout(() => {
scaleItem(star, 0, 0.3, () => {
parent.removeChild(star);
});
}, 100 + Math.random() * 200);
});
}
}
\ No newline at end of file
.game-container {
width: 100%;
height: 100%;
background: #ffffff;
background-size: cover;
}
#canvas {
}
@font-face
{
font-family: 'BRLNSDB';
src: url("../../assets/font/BRLNSDB.TTF") ;
}
.game-container {
width: 100%;
height: 100%;
//background-image: url("/assets/play/listen-read-circle/bg.jpg");
background: #ffffff;
background-repeat: no-repeat;
background-size: cover;
}
.read-and-point-copy {
width: 500px;
height: 85px;
object-fit: contain;
text-shadow: 0 6px 4px rgba(0, 0, 0, 0.5), 0 3px 0 #fffecc;
font-family: Questrian;
font-size: 72px;
font-weight: normal;
font-stretch: normal;
font-style: normal;
line-height: normal;
letter-spacing: normal;
color: #f8e424;
}
.read-and-point-copy .text-style-1 {
font-size: 48px;
}
.read-and-point-copy .text-style-2 {
font-size: 64px;
}
@font-face
{
font-family: 'BRLNSDB';
src: url("../../assets/play/font/BRLNSDB.TTF") ;
}
@font-face
{
font-family: 'RoundedBold';
src: url("../../assets/play/font/ArialRoundedBold.otf") ;
}
@font-face{
font-family: 'BRLNSB_1';
src: url("../../assets/play/font/BerlinSansFB/BRLNSB_1.TTF") ;
}
@font-face{
font-family: 'BerlinSansFBDemi-Bold';
src: url("../../assets/play/font/BerlinSansFB/BRLNSDB_1.TTF") ;
}
@font-face{
font-family: 'BRLNSR_1';
src: url("../../assets/play/font/BerlinSansFB/BRLNSR_1.TTF") ;
}
@font-face{
font-family: 'GOTHIC_1';
src: url("../../assets/play/font/CenturyGothic/GOTHIC_1.TTF") ;
}
@font-face{
font-family: 'GOTHICB_1';
src: url("../../assets/play/font/CenturyGothic/GOTHICB_1.TTF") ;
}
@font-face{
font-family: 'GOTHICBI_1';
src: url("../../assets/play/font/CenturyGothic/GOTHICBI_1.TTF") ;
}
@font-face{
font-family: 'GOTHICI_1';
src: url("../../assets/play/font/CenturyGothic/GOTHICI_1.TTF") ;
}
@font-face{
font-family: 'MMTextBook';
src: url("../../assets/play/font/MMTextBook/MMTextBook.otf") ;
}
@font-face{
font-family: 'MMTextBook-Bold';
src: url("../../assets/play/font/MMTextBook/MMTextBook-Bold.otf") ;
}
@font-face{
font-family: 'MMTextBook-BoldItalic';
src: url("../../assets/play/font/MMTextBook/MMTextBook-BoldItalic.otf") ;
}
@font-face{
font-family: 'MMTextBook-Italic';
src: url("../../assets/play/font/MMTextBook/MMTextBook-Italic.otf") ;
}
@font-face{
font-family: 'FuturaBT-Bold';
src: url("../../assets/play/font/FUTURAB.ttf") ;
}
\ No newline at end of file
import {Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener} from '@angular/core'; import {
Component,
ElementRef,
ViewChild,
OnInit,
Input,
OnDestroy,
HostListener
} from "@angular/core";
import { UUID } from 'angular2-uuid';
import { import {
MySprite,
RichText,
getMinScale,
ShapeRect,
ShapeCircle,
tweenChange,
randomSortByArr,
Label, Label,
MySprite, tweenChange, showPopParticle,
moveItem,
removeItemFromArr,
rotateItem,
hideItem,
showItem,
ShapeRectNew,
scaleItem,
showBlingBling,
waterWave,
jelly,
getAngleByPos,
getPosDistance,
shake
} from "./Unit";
import { localImages, localAudios, multiSizeBackground} from "./resources";
import { Cartoon } from './Cartoon'
import { Subject } from "rxjs";
import { debounceTime, map, takeWhile, retry } from "rxjs/operators";
import * as _ from "lodash";
import TWEEN from "@tweenjs/tween.js";
import defauleFormData from '../../assets/play/default/formData/defaultData.js'
const zIndexMap = {
mainBackground: 0,
boy: 10,
mainDesk: 20,
Curtain_A: 100,
Curtain_B: 100,
Curtain_C: 99,
Curtain_D: 99,
Curtain_E: 110,
startButton: 120,
liewen: 41,
answerCard: 45,
questionCard: 50,
mainQuestionImage: 35,
imageContainer:35,
imageBackground: 36,
shortAudio: 40,
animation: 80,
popUp: 90,
buttons: 100
}
} from './Unit'; @Component({
import {res, resAudio} from './resources'; selector: "app-play",
templateUrl: "./play.component.html",
styleUrls: ["./play.component.scss"]
})
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import TWEEN from '@tweenjs/tween.js';
export class PlayComponent implements OnInit, OnDestroy {
g_cartoon = new Cartoon()
// ------------ 全局数据 ------------
g_stage; //中心舞台
// g_background_color = "#rgb(0,0,0,0)"
g_background_color = "#ffe197"
g_enableMapDown = true; // 触摸使能
g_enableMapUp = true; // 抬起使能
g_enableMapMove = true; // 移动ss使能
g_canvasLeft;
g_canvasTop;
g_animationId: any;
g_mapScale = 1; // 缩放比例
g_KEY = "DataKey_East_L226";
g_canvasWidth = 1280;
g_canvasHeight = 720;
g_canvasBaseW = 1280;
g_canvasBaseH = 720;
g_winResizeEventStream = new Subject();
g_clickX; // 点击坐标 X
g_clickY; // 点击坐标 Y
g_ctx; // canvas 实例
g_data; // 数据
g_formData; // 核心表单数据
g_teacherFlag = false; // 默认角色
g_currentUser;
g_firstTouch = true;
g_partTitle_x = null;
g_mainTitle_x = null;
// ------------------------------------
// ------------ 私有数据 ------------
m_mapDownQueue = {} //按下事件处理队列
m_mapDownArray = [] //按下事件处理队列
m_mapDownObject = []
m_mapUpQueue = {} //抬起事件处理队列
m_mapUpArray = [] //抬起事件处理队列
m_mapUpObject = []
m_mapMoveArray = [] //移动事件处理队列
m_mapMoveObject = []
m_endPageArr;
m_showPetalFlag;
m_elementPetalArr;
m_showElementPetalFlag;
m_PetalImage = "_scrap-pic-" // 飘落动画
m_renderArr // 渲染队列
m_renderObject = [];
m_defaultZindex = 0;
m_setTimeoutIDs = [];
m_setIntervalIDs = [];
m_moveAsstantIntervalId = null;
// ------------------------------------
// ------------ 游戏逻辑数据 ------------
// ------------------------------------
// ------------ 消息 ------------
// ------------------------------------
// ------------ 调试变量 ------------
g_EnableStageRuler = false; // 使能舞台背景格尺
g_ForceChangeDefaultRole = false // 强制当前角色为默认角色
g_EnableTestSendEvent = false // 发送模拟Web数据
g_showLeftCornerTest= false // 测试左上角图标
// ------------------------------------
// 当数据加载完毕后,执行
systemReady(){
this.setLeftCornerTest()
this.initGame()
}
// 屏幕尺寸变化后执行
handleScreenResize(){
this.initSystem();
this.cleanSystemVar()
this.cleanGameVar();
this.setLeftCornerTest()
this.initGame()
}
// 映射预加载图片[网路]资源 返回包含图片路径的数组
mapToImageArray(contentObj){
let array = []
this.g_formData.dataArray.forEach(element => {
if(element.image_url){
array.push(element.image_url)
}
});
@Component({ return array
selector: 'app-play', }
templateUrl: './play.component.html',
styleUrls: ['./play.component.css']
})
export class PlayComponent implements OnInit, OnDestroy {
@ViewChild('canvas', {static: true }) canvas: ElementRef; // 映射预加载音频[网路]资源 返回包含音频路径的数组
@ViewChild('wrap', {static: true }) wrap: ElementRef; mapToAduioArray(contentObj){
let array = []
// 数据 this.g_formData.dataArray.forEach(element => {
data; if(element.image_url){
array.push(element.audio_url)
}
});
ctx; return array
}
canvasWidth = 1280; // canvas实际宽度 // ------------------------------------------------------------------------------
canvasHeight = 720; // canvas实际高度 // 游戏核心处理区
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
initGame(){
console.log(this.g_formData);
this.initBackground();
this.initBoy();
this.initCurtain();
this.initStartButton();
this.initRestartButton()
}
canvasBaseW = 1280; // canvas 资源预设宽度 cleanGameVar(){
canvasBaseH = 720; // canvas 资源预设高度
mx; // 点击x坐标 }
my; // 点击y坐标
startGame(){
// 资源 }
rawImages = new Map(res);
rawAudios = new Map(resAudio);
images = new Map(); restartGame(){
this.cleanGameVar()
this.startGame()
}
animationId: any; endGame(){
winResizeEventStream = new Subject(); this.curtainContral(false, ()=>{
this.g_cartoon.getCartoonElement("restart-button").in()
this.g_cartoon.getCartoonElement("boy").endReadyAni()
this.g_enableMapDown = true;
})
}
audioObj = {}; initBackground(){
let mainBG = this.g_cartoon.createCartoonElementImageFunc("main-background", "background", (w ,h)=>{
return {
sx: this.g_canvasWidth / w,
sy: this.g_canvasHeight / h
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 2,
y: this.g_canvasHeight / 2,
}
})
this.render(mainBG.ref, zIndexMap.mainBackground)
renderArr; let bg_Desk = this.g_cartoon.createCartoonElementImageFunc("main-background-desk", "hengban", (w ,h)=>{
mapScale = 1; return {
sx: this.g_canvasWidth / w,
sy: 84 * this.g_mapScale / h
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 2,
y: this.g_canvasHeight / 2 + 315 * this.g_mapScale
}
})
this.render(bg_Desk.ref, zIndexMap.mainDesk)
canvasLeft; let bg_Light = this.g_cartoon.createCartoonElementImageFunc("main-background-desk", "dengqiu1", (w ,h)=>{
canvasTop; return {
sx: 1032 * this.g_mapScale / w,
sy: 317 * this.g_mapScale / h
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 2,
y: this.g_canvasHeight / 2 - 200 * this.g_mapScale
}
})
this.render(bg_Light.ref, zIndexMap.mainBackground + 2)
}
saveKey = 'test_0011'; initBoy(){
let element = this.g_cartoon.createCartoonElementImageFunc("boy", "boy_1", (w ,h)=>{
return {
sx: 550 * this.g_mapScale / w,
sy: 800 * this.g_mapScale / h
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 2,
y: this.g_canvasHeight / 2 + 70 * this.g_mapScale
}
})
this.render(element.ref, zIndexMap.boy)
element.ref.visible = true
element.play = this.g_cartoon.createAnimation("boy", 30, 500)
element.play.x = this.g_canvasWidth / 2;
element.play.y = this.g_canvasHeight / 2 + 70 * this.g_mapScale
element.play.scaleX = element.ref.scaleX
element.play.scaleY = element.ref.scaleY
element.play.loop = true;
element.isPlay = false;
element.play.visible = false;
this.render(element.play, zIndexMap.boy)
element.startReadyAni = ()=>{
element.play.play()
element.ref.visible = false
element.play.visible = true
element.isPlay = true;
}
element.endReadyAni = ()=>{
element.play.stop()
element.ref.visible = true
element.play.visible = false
element.isPlay = false;
}
btnLeft; }
btnRight;
pic1;
pic2;
canTouch = true; initCurtain(){
let A = this.g_cartoon.createCartoonElementImageFunc("Curtain-A", "lianzir", (w ,h)=>{
return {
sx: 357 * this.g_mapScale / w,
sy: 720 * this.g_mapScale / h
}
}, (w, h)=>{
return {
x: 357 * this.g_mapScale / 2,
y: this.g_canvasHeight / 2
}
})
this.render(A.ref, zIndexMap.Curtain_A)
A.open = ()=>{
this.m_setTimeoutIDs.push(setTimeout(() => {
tweenChange(A.ref, {x: (-357 / 2 + 100) * this.g_mapScale}, 3)
}, 3000))
}
A.close = ()=>{
this.m_setTimeoutIDs.push(setTimeout(() => {
tweenChange(A.ref, {x: A.initX}, 3)
}, 3000))
}
curPic; let B = this.g_cartoon.createCartoonElementImageFunc("Curtain-B", "lianzil", (w ,h)=>{
return {
sx: 357 * this.g_mapScale / w,
sy: 720 * this.g_mapScale / h
}
}, (w, h)=>{
return {
x: this.g_canvasWidth - 357 * this.g_mapScale / 2,
y: this.g_canvasHeight / 2
}
})
this.render(B.ref, zIndexMap.Curtain_B)
B.open = ()=>{
this.m_setTimeoutIDs.push(setTimeout(() => {
tweenChange(B.ref, {x: this.g_canvasWidth + (357 / 2 - 100) * this.g_mapScale}, 3)
}, 3000))
}
B.close = ()=>{
this.m_setTimeoutIDs.push(setTimeout(() => {
tweenChange(B.ref, {x: B.initX}, 3)
}, 3000))
}
@HostListener('window:resize', ['$event']) let C = this.g_cartoon.createCartoonElementImageFunc("Curtain-C", "lianzi4", (w ,h)=>{
onResize(event) { return {
this.winResizeEventStream.next(); sx: this.g_canvasWidth / 2 / w,
sy: 720 * this.g_mapScale / h
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 4,
y: this.g_canvasHeight / 2
}
})
this.render(C.ref, zIndexMap.Curtain_C)
C.open = ()=>{
tweenChange(C.ref, {x: -this.g_canvasWidth / 4}, 7)
}
C.close = ()=>{
tweenChange(C.ref, {x: C.initX}, 7)
}
let D = this.g_cartoon.createCartoonElementImageFunc("Curtain-D", "lianzi3", (w ,h)=>{
return {
sx: this.g_canvasWidth / 2 / w,
sy: 720 * this.g_mapScale / h
}
}, (w, h)=>{
return {
x: this.g_canvasWidth - this.g_canvasWidth / 4 - 10 * this.g_mapScale,
y: this.g_canvasHeight / 2
}
})
this.render(D.ref, zIndexMap.Curtain_D)
D.open = ()=>{
tweenChange(D.ref, {x: this.g_canvasWidth + this.g_canvasWidth / 4}, 7)
}
D.close = ()=>{
tweenChange(D.ref, {x: D.initX}, 7)
}
let E = this.g_cartoon.createCartoonElementImageFunc("Curtain-E", "lianzi0", (w ,h)=>{
return {
sx: this.g_canvasWidth / w,
sy: 95 * this.g_mapScale / h
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 2,
y: (95 / 2) * this.g_mapScale
}
})
this.render(E.ref, zIndexMap.Curtain_E)
} }
curtainContral(status, callback?){
let all = ["Curtain-A", "Curtain-B", "Curtain-C", "Curtain-D"]
if(status){
all.forEach(item=>{
this.g_cartoon.getCartoonElement(item).open()
})
}else{
all.forEach(item=>{
this.g_cartoon.getCartoonElement(item).close()
})
}
this.m_setTimeoutIDs.push(setTimeout(()=>{
callback && callback()
}, 7000))
}
initStartButton(){
let element = this.g_cartoon.createCartoonElementImageFunc("start-button", "btn_start", (w ,h)=>{
return {
sx: 331 * this.g_mapScale / w,
sy: 112 * this.g_mapScale / h
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 2 + 450 * this.g_mapScale,
y: this.g_canvasHeight / 2 + 250 * this.g_mapScale
}
})
this.render(element.ref, zIndexMap.startButton)
this.subscribeMapDownEvent(element.id, ()=>{
this.showJellyAnimation(element.id, ()=>{
tweenChange(element.ref, {x: this.g_canvasWidth + 331 * this.g_mapScale}, 0.5)
})
this.g_cartoon.getCartoonElement("boy").startReadyAni()
this.startGame()
this.curtainContral(true, ()=>{
this.g_enableMapDown = true;
})
})
}
initRestartButton(){
let element = this.g_cartoon.createCartoonElementImageFunc("restart-button", "restart", (w ,h)=>{
return {
sx: 331 * this.g_mapScale / w,
sy: 112 * this.g_mapScale / h
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 2 + 450 * this.g_mapScale,
y: this.g_canvasHeight / 2 + 250 * this.g_mapScale
}
})
element.ref.x = this.g_canvasWidth + 331 * this.g_mapScale
this.render(element.ref, zIndexMap.startButton)
element.in = (callback?)=>{
tweenChange(element.ref, {x: element.initX}, 0.5, ()=>{
callback && callback()
})
}
element.out = (callback?)=>{
tweenChange(element.ref, {x: this.g_canvasWidth + 331 * this.g_mapScale}, 0.5, ()=>{
callback && callback()
})
}
this.subscribeMapDownEvent(element.id, ()=>{
this.showJellyAnimation(element.id, ()=>{
element.out()
})
this.restartGame()
this.g_cartoon.getCartoonElement("boy").startReadyAni()
this.curtainContral(true, ()=>{
this.g_enableMapDown = true;
})
})
}
ngOnInit() {
this.data = {};
// 获取数据
const getData = (<any> window).courseware.getData;
getData((data) => {
if (data && typeof data == 'object') {
this.data = data;
// --------------------------------------------------
// -------------- Template function ---------------
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
//
// _________
// / /.
// .-------------. /_________/ |
// / / | | | |
// /+============+\ | | |====| | |
// ||C:\> || | | | |
// || || | | |====| | |
// || || | | ___ | |
// || || | | |166| | |
// || ||/@@@ | --- | |
// \+============+/ @ |_________|./.
// @ .. ....'
// ..................@ __.'.' ''
// /oooooooooooooooo// ///
// /................// /_/
// ------------------
//
// --------------------------------------------------
@ViewChild("canvas") canvas: ElementRef;
@ViewChild("wrap") wrap: ElementRef;
@HostListener("window:resize", ["$event"])
onResize(event) {
this.g_winResizeEventStream.next();
}
ngOnDestroy() {
window["curCtx"] = null;
window.cancelAnimationFrame(this.g_animationId);
}
ngOnInit() {
const getData = (<any>window).courseware.getData;
getData(data => {
if (window['air'].airClassInfo.user.classRole == 'tea') {
if(!this.g_ForceChangeDefaultRole){
this.g_teacherFlag = true;
}
}
this.g_currentUser = window['air'].airClassInfo.user;
if (data && typeof data == "object") {
this.g_data = data;
this.g_formData = data.contentObj;
} else {
this.g_data = {};
} }
// console.log('data:' , data);
// 初始化 各事件监听
this.initListener(); if (!this.g_data.contentObj) {
this.g_data.contentObj = {};
this.g_formData = {};
}
// 若无数据 则为预览模式 需要填充一些默认数据用来显示
this.initDefaultData(); this.initDefaultData();
// 初始化 音频资源
this.initAudio(); this.initAudio();
// 初始化 图片资源
this.initImg(); this.initImg();
// 开始预加载资源
this.load();
}, this.saveKey); // 预加载资源
this.g_cartoon.loadResources().then(() => {
window["air"].hideAirClassLoading(this.g_KEY, this.g_data);
this.initSystem();
this.update();
this.systemReady()
});
this.initListener();
}, this.g_KEY);
} }
ngOnDestroy() { // ----------------------------------
window['curCtx'] = null; // 初始化默认数据
window.cancelAnimationFrame(this.animationId); // ----------------------------------
initDefaultData() {
if ( Object.keys(this.g_formData).length===0 || this.g_formData.version != defauleFormData.version ) {
this.g_formData = defauleFormData;
}
} }
load() { // ----------------------------------
// 初始化音乐
// 预加载资源 // ----------------------------------
this.loadResources().then(() => { initAudio() {
window["air"].hideAirClassLoading(this.saveKey, this.data); const contentObj = this.g_formData;
this.init(); if (!contentObj) {
this.update(); return;
}
// 添加用户上传音效
let images:Array<string> = this.mapToAduioArray(contentObj)
images.forEach(image => {
this.g_cartoon.addAudio( image, image );
}); });
// 添加本地音效
for( var key in localAudios ){
this.g_cartoon.addAudio( key, localAudios[key] );
}
} }
// ----------------------------------
// 初始化图片
// ----------------------------------
initImg() {
const contentObj = this.g_formData;
if (contentObj) {
const addPicUrl = url => {
if (url) {
this.g_cartoon.addImage(url, url);
}
};
let images:Array<string> = this.mapToImageArray(contentObj)
images.forEach(image => {
addPicUrl(image)
});
}
// 添加本地图片
for( var key in localImages ){
this.g_cartoon.addImage( key, localImages[key] );
}
}
init() {
this.initCtx(); mapDown(event) {
this.initData(); let myStopPropagation = false;
this.initView(); if (!this.g_enableMapDown) {
} return;
}
console.log("All click event subscribers:", this.m_mapDownArray)
this.m_mapDownArray.forEach((item)=>{
if(!myStopPropagation){
if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(item.id))) {
this.g_enableMapDown = false;
console.log("Click event - target id:["+item.id+"]")
if(item.callback()){
myStopPropagation = true;
}
}
}
})
initCtx() {
this.canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight;
this.canvas.nativeElement.width = this.wrap.nativeElement.clientWidth;
this.canvas.nativeElement.height = this.wrap.nativeElement.clientHeight;
}
this.ctx = this.canvas.nativeElement.getContext('2d'); mapMove(event) {
this.canvas.nativeElement.width = this.canvasWidth; let myStopPropagation = false;
this.canvas.nativeElement.height = this.canvasHeight; if (!this.g_enableMapMove) {
return;
}
window['curCtx'] = this.ctx; this.m_mapMoveArray.forEach((item)=>{
if(!myStopPropagation){
if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(item.id))) {
this.g_enableMapMove = false;
if(item.callback()){
myStopPropagation = true;
}
}
}
})
} }
mapUp(event) {
let myStopPropagation = false;
if (!this.g_enableMapUp) {
return;
}
// for(let cartoonID in this.m_mapUpQueue){
// if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(cartoonID))) {
// this.g_enableMapUp = false;
// this.m_mapUpQueue[cartoonID]();
// }
// }
this.m_mapUpArray.forEach((item)=>{
if(!myStopPropagation){
if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(item.id))) {
this.g_enableMapUp = false;
if(item.callback()){
myStopPropagation = true;
}
}
}
})
}
update() {
this.g_animationId = window.requestAnimationFrame(this.update.bind(this));
// 清除画布内容
this.g_ctx.clearRect(0, 0, this.g_canvasWidth, this.g_canvasHeight);
TWEEN.update();
this.updateArr(this.m_renderArr);
this.updateArr(this.m_endPageArr);
this.updateArr(this.m_elementPetalArr);
}
updateItem(item) { updateItem(item) {
...@@ -154,6 +734,7 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -154,6 +734,7 @@ export class PlayComponent implements OnInit, OnDestroy {
} }
} }
updateArr(arr) { updateArr(arr) {
if (!arr) { if (!arr) {
return; return;
...@@ -164,49 +745,39 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -164,49 +745,39 @@ export class PlayComponent implements OnInit, OnDestroy {
} }
initListener() { initListener() {
const element = this.canvas.nativeElement;
this.winResizeEventStream this.g_winResizeEventStream.pipe(debounceTime(500)).subscribe(data => {
.pipe(debounceTime(500)) this.renderAfterResize();
.subscribe(data => { });
this.renderAfterResize();
}); const addTouchListener = () => {
element.addEventListener('touchstart', touchDownFunc);
element.addEventListener('touchmove', touchMoveFunc);
// --------------------------------------------- element.addEventListener('touchend', touchUpFunc);
const setParentOffset = () => { element.addEventListener('touchcancel', touchUpFunc);
const rect = this.canvas.nativeElement.getBoundingClientRect();
this.canvasLeft = rect.left;
this.canvasTop = rect.top;
}; };
const setMxMyByTouch = (event) => { const removeTouchListener = () => {
if (event.touches.length <= 0) { element.removeEventListener('touchstart', touchDownFunc);
return; element.removeEventListener('touchmove', touchMoveFunc);
} element.removeEventListener('touchend', touchUpFunc);
if (this.canvasLeft == null) { element.removeEventListener('touchcancel', touchUpFunc);
setParentOffset();
}
this.mx = event.touches[0].pageX - this.canvasLeft;
this.my = event.touches[0].pageY - this.canvasTop;
}; };
const setMxMyByMouse = (event) => { const addMouseListener = () => {
this.mx = event.offsetX; element.addEventListener('mousedown', mouseDownFunc);
this.my = event.offsetY; element.addEventListener('mousemove', mouseMoveFunc);
element.addEventListener('mouseup', mouseUpFunc);
};
const removeMouseListener = () => {
element.removeEventListener('mousedown', mouseDownFunc);
element.removeEventListener('mousemove', mouseMoveFunc);
element.removeEventListener('mouseup', mouseUpFunc);
}; };
// ---------------------------------------------
let firstTouch = true;
const touchDownFunc = (e) => { const touchDownFunc = (e) => {
if (firstTouch) { if (this.g_firstTouch) {
firstTouch = false; this.g_firstTouch = false;
removeMouseListener(); removeMouseListener();
} }
setMxMyByTouch(e); setMxMyByTouch(e);
...@@ -222,8 +793,8 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -222,8 +793,8 @@ export class PlayComponent implements OnInit, OnDestroy {
}; };
const mouseDownFunc = (e) => { const mouseDownFunc = (e) => {
if (firstTouch) { if (this.g_firstTouch) {
firstTouch = false; this.g_firstTouch = false;
removeTouchListener(); removeTouchListener();
} }
setMxMyByMouse(e); setMxMyByMouse(e);
...@@ -238,135 +809,85 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -238,135 +809,85 @@ export class PlayComponent implements OnInit, OnDestroy {
this.mapUp(e); this.mapUp(e);
}; };
const setMxMyByTouch = event => {
const element = this.canvas.nativeElement; if (event.touches.length <= 0) {
return;
const addTouchListener = () => { }
element.addEventListener('touchstart', touchDownFunc); if (this.g_canvasLeft == null) {
element.addEventListener('touchmove', touchMoveFunc); setParentOffset();
element.addEventListener('touchend', touchUpFunc); }
element.addEventListener('touchcancel', touchUpFunc); this.g_clickX = event.touches[0].pageX - this.g_canvasLeft;
}; this.g_clickY = event.touches[0].pageY - this.g_canvasTop;
const removeTouchListener = () => {
element.removeEventListener('touchstart', touchDownFunc);
element.removeEventListener('touchmove', touchMoveFunc);
element.removeEventListener('touchend', touchUpFunc);
element.removeEventListener('touchcancel', touchUpFunc);
}; };
const addMouseListener = () => { const setParentOffset = () => {
element.addEventListener('mousedown', mouseDownFunc); const rect = this.canvas.nativeElement.getBoundingClientRect();
element.addEventListener('mousemove', mouseMoveFunc); this.g_canvasLeft = rect.left;
element.addEventListener('mouseup', mouseUpFunc); this.g_canvasTop = rect.top;
}; };
const removeMouseListener = () => {
element.removeEventListener('mousedown', mouseDownFunc); const setMxMyByMouse = (event) => {
element.removeEventListener('mousemove', mouseMoveFunc); this.g_clickX = event.offsetX;
element.removeEventListener('mouseup', mouseUpFunc); this.g_clickY = event.offsetY;
}; };
addMouseListener(); addMouseListener();
addTouchListener(); addTouchListener();
} }
showArr(arr) {
playAudio(key, now = false, callback = null) { if (!arr) {
return;
const audio = this.audioObj[key]; }
if (audio) { for (let i = 0; i < arr.length; i++) {
if (now) { arr[i].visible = true;
audio.pause();
audio.currentTime = 0;
}
if (callback) {
audio.onended = () => {
callback();
};
}
audio.play();
} }
} }
hideArr(arr) {
if (!arr) {
loadResources() { return;
const pr = []; }
this.rawImages.forEach((value, key) => {// 预加载图片 for (let i = 0; i < arr.length; i++) {
arr[i].visible = false;
const p = this.preload(value) }
.then(img => {
this.images.set(key, img);
})
.catch(err => console.log(err));
pr.push(p);
});
this.rawAudios.forEach((value, key) => {// 预加载音频
const a = this.preloadAudio(value)
.then(() => {
// this.images.set(key, img);
})
.catch(err => console.log(err));
pr.push(a);
});
return Promise.all(pr);
}
preload(url) {
return new Promise((resolve, reject) => {
const img = new Image();
// img.crossOrigin = "anonymous";
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
} }
preloadAudio(url) { IsPC() {
return new Promise((resolve, reject) => { if (window["ELECTRON"]) {
const audio = new Audio(); return false; // 封装客户端标记
audio.oncanplay = (a) => { }
resolve(); if (
}; document.body.ontouchmove !== undefined &&
audio.onerror = () => { document.body.ontouchmove !== undefined
reject(); ) {
}; return false;
audio.src = url; } else {
audio.load(); return true;
}); }
} }
renderAfterResize() { renderAfterResize() {
this.canvasWidth = this.wrap.nativeElement.clientWidth; this.g_canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight; this.g_canvasHeight = this.wrap.nativeElement.clientHeight;
this.init(); this.update();
this.handleScreenResize()
} }
checkClickTarget(target) { checkClickTarget(target) {
if (!target) {
return false;
}
const rect = target.getBoundingBox(); const rect = target.getBoundingBox();
if (this.checkPointInRect(this.g_clickX, this.g_clickY, rect)) {
if (this.checkPointInRect(this.mx, this.my, rect)) {
return true; return true;
} }
return false; return false;
} }
getWorlRect(target) { getWorlRect(target) {
let rect = target.getBoundingBox(); let rect = target.getBoundingBox();
if (target.parent) { if (target.parent) {
const pRect = this.getWorlRect(target.parent); const pRect = this.getWorlRect(target.parent);
rect.x += pRect.x; rect.x += pRect.x;
rect.y += pRect.y; rect.y += pRect.y;
...@@ -384,296 +905,625 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -384,296 +905,625 @@ export class PlayComponent implements OnInit, OnDestroy {
} }
getPosByAngle(angle, len) {
const radian = (angle * Math.PI) / 180;
const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len;
return { x, y };
}
getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx;
const _y = ey - sy;
const len = Math.sqrt(Math.pow(_x, 2) + Math.pow(_y, 2));
return len;
}
addUrlToAudioObj(key, url = null, vlomue = 1, loop = false, callback = null) {
const audioObj = this.audioObj;
if (url == null) {
url = key;
}
this.rawAudios.set(key, url);
const audio = new Audio();
audio.src = url;
audio.load();
audio.loop = loop;
audio.volume = vlomue;
audioObj[key] = audio;
if (callback) { subscribeMapDownEvent(id,callback, zIndex?){
audio.onended = () => { zIndex = zIndex?zIndex:0
callback(); this.m_mapDownObject.push({id:id, zIndex:zIndex?zIndex:1, callback:callback})
}; this.m_mapDownObject.sort((a,b)=>{
} return b.zIndex-a.zIndex
})
this.m_mapDownArray = []
this.m_mapDownObject.forEach(item=>{
this.m_mapDownArray.push(item)
})
} }
addUrlToImages(url) { subscribeMapUpEvent(id,callback, zIndex?){
this.rawImages.set(url, url); zIndex = zIndex?zIndex:0
this.m_mapUpObject.push({id:id, zIndex:zIndex?zIndex:1, callback:callback})
this.m_mapUpObject.sort((a,b)=>{
return b.zIndex-a.zIndex
})
this.m_mapUpArray = []
this.m_mapUpObject.forEach(item=>{
this.m_mapUpArray.push(item)
})
} }
subscribeMapMoveEvent(id, callback, zIndex?){
zIndex = zIndex?zIndex:0
this.m_mapMoveObject.push({id:id, zIndex:zIndex?zIndex:1, callback:callback})
this.m_mapMoveObject.sort((a,b)=>{
return a.zIndex - b.zIndex
})
this.m_mapMoveArray = []
this.m_mapMoveObject.forEach(item=>{
this.m_mapMoveArray.push(item)
})
}
// 全局初始化入口,当资源加载完毕后执行
initSystem() {
this.g_canvasWidth = this.wrap.nativeElement.clientWidth;
this.g_canvasHeight = this.wrap.nativeElement.clientHeight;
const sx = this.g_canvasWidth / this.g_canvasBaseW;
const sy = this.g_canvasHeight / this.g_canvasBaseH;
const s = Math.min(sx, sy);
this.g_mapScale = s;
this.g_cartoon.mapScale = this.g_mapScale;
this.g_cartoon.clientWidth = this.wrap.nativeElement.clientWidth;
this.g_cartoon.clientHeight = this.wrap.nativeElement.clientHeight;
// ======================================================编写区域========================================================================== this.m_renderArr = [];
this.m_renderObject = [];
this.g_enableMapDown = true;
this.g_ctx = this.canvas.nativeElement.getContext("2d");
this.canvas.nativeElement.width = this.g_canvasWidth;
this.canvas.nativeElement.height = this.g_canvasHeight;
window["curCtx"] = this.g_ctx;
// 初始化舞台
this.initStage();
this.update();
}
initStage() {
const bgWidth = 1280;
const bgHeight = 720;
this.g_cartoon.stageWidth = bgWidth*this.g_mapScale;
this.g_cartoon.stageHeight= bgHeight*this.g_mapScale;
const imageColor = this.g_cartoon.createCartoonElement("background-color", "ShapeRect").ref;
// console.log( "stageWidth: " + this.g_cartoon.stageWidth + " stageHeight" + this.g_cartoon.stageHeight)
// console.log( "clientWidth: " + this.g_cartoon.clientWidth + " clientHeight" + this.g_cartoon.clientHeight)
// console.log( "canvasWidth: " + this.g_canvasWidth + " canvasHeight" + this.g_canvasHeight)
// console.log( "mapScale: " + this.g_mapScale )
imageColor.x = this.g_cartoon.clientWidth / 2 ;
imageColor.y = this.g_cartoon.clientHeight / 2 ;
imageColor.setSize(this.g_cartoon.clientWidth, this.g_cartoon.clientHeight);
imageColor.init();
imageColor.fillColor = this.g_background_color;
this.render(imageColor, -999999)
const image = this.g_cartoon.createCartoonElement("bg_1280_720_Ruler", "MySprite").ref;
image.init(this.g_cartoon.images.get("_bg_1280_720_Ruler"));
image.x = this.g_canvasWidth / 2;
image.y = this.g_canvasHeight /2;
image.visible = this.g_EnableStageRuler
this.g_cartoon.setOrigin( image.x-(bgWidth/2*this.g_mapScale), image.y-(bgHeight/2*this.g_mapScale) )
this.g_cartoon.setRelativeOrigin( -bgWidth/2, -bgHeight/2)
image.setScaleXY(this.g_mapScale);
this.render(image, -999)
this.g_stage = image
}
render(ele, zIndex?:number){
this.m_renderObject.push({element:ele, zIndex:zIndex?zIndex:1})
this.m_renderObject.sort((a,b)=>{
return a.zIndex - b.zIndex
})
this.m_renderArr = []
this.m_renderObject.forEach(item=>{
this.m_renderArr.push(item.element)
})
}
sendServerEvent(key, data) {
const c = (<any> window).courseware;
c.sendEvent(key, JSON.stringify(data));
}
/** addServerListener(msg_key, callback) {
* 添加默认数据 便于无数据时的展示 const c = (<any> window).courseware;
*/ c.onEvent(msg_key, (data,next) => {
initDefaultData() { callback(JSON.parse(data))
next && next();
});
}
if (!this.data.pic_url) { randomArray_shuffle(array) {
this.data.pic_url = 'assets/play/default/pic.jpg'; var input = array;
this.data.pic_url_2 = 'assets/play/default/pic.jpg'; for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
} }
return input;
} }
paginationArray(pageNo, pageSize, array) {
/** var offset = (pageNo - 1) * pageSize;
* 添加预加载图片 return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
*/
initImg() {
this.addUrlToImages(this.data.pic_url);
this.addUrlToImages(this.data.pic_url_2);
} }
/** stopAllTimeout(){
* 添加预加载音频 this.m_setTimeoutIDs.forEach(id=>clearTimeout(id))
*/ this.m_setTimeoutIDs = []
initAudio() { }
// 音频资源 stopAllInterval(){
this.addUrlToAudioObj(this.data.audio_url); this.m_setIntervalIDs.forEach(id=>clearInterval(id))
this.addUrlToAudioObj(this.data.audio_url_2); this.m_setIntervalIDs = []
}
// 音效 topOfRenderArray(element){
this.addUrlToAudioObj('click', this.rawAudios.get('click'), 0.3); let index = this.m_renderArr.indexOf(element)
if(index !=-1){
this.m_renderArr.splice(index, 1)
this.m_renderArr.push(element)
}
}
setRenderZIndex(element, zIndex){
let index = null;
for(let i=0; i<this.m_renderObject.length; i++){
if( this.m_renderObject[i].element.id == element.id ){
index = i
}
}
if(index){
this.m_renderObject.splice(index, 1)
this.m_renderObject.push({element:element, zIndex:zIndex?zIndex:1})
this.m_renderObject.sort((a,b)=>{
return a.zIndex - b.zIndex
})
this.m_renderArr = []
this.m_renderObject.forEach(item=>{
this.m_renderArr.push(item.element)
})
}
}
deleteElementInRender(id){
let index = null;
for(let i=0; i<this.m_renderObject.length; i++){
if( this.m_renderObject[i].element.id == id ){
index = i
}
}
if(index){
this.m_renderObject.splice(index, 1)
this.m_renderObject.sort((a,b)=>{
return a.zIndex - b.zIndex
})
this.m_renderArr = []
this.m_renderObject.forEach(item=>{
this.m_renderArr.push(item.element)
})
}else{
console.warn("Can not found element id:" + id)
}
} }
enableMoveAsstant(callback){
if(this.m_moveAsstantIntervalId){
clearInterval(this.m_moveAsstantIntervalId)
}
this.m_moveAsstantIntervalId = setInterval(()=>{
callback()
},50)
}
disableMoveAsstant(){
clearInterval(this.m_moveAsstantIntervalId)
}
/** cleanSystemVar(){
* 初始化数据 this.m_mapDownQueue = {}
*/ this.m_mapDownArray = []
initData() { this.m_mapDownObject = []
this.m_mapMoveArray = []
this.m_mapMoveObject = []
this.m_mapUpQueue = {}
this.m_mapUpArray = []
this.m_mapUpObject = []
this.stopAllInterval();
this.stopAllTimeout()
this.g_cartoon.stopAllAudio()
}
const sx = this.canvasWidth / this.canvasBaseW; getMaxSubstringLength(str){
const sy = this.canvasHeight / this.canvasBaseH; let maxLength = 0;
const s = Math.min(sx, sy); let subSubstring = str.split(" ")
this.mapScale = s; for (let index=0; index<subSubstring.length; index++) {
if(subSubstring[index].length > maxLength){
maxLength = subSubstring[index].length;
}
}
return maxLength
}
// this.mapScale = sx; setLeftCornerTest(){
// this.mapScale = sy; const bgRect = new ShapeRect();
bgRect.setSize(57, 65);
bgRect.fillColor = '#f8c224';
const sx = this.g_canvasWidth / this.g_canvasBaseW;
bgRect.setScaleXY(sx);
bgRect.x = 65 * sx;
this.g_partTitle_x = bgRect.x
this.g_mainTitle_x = bgRect.x + 80 * sx
bgRect.alpha = 0.5
bgRect.visible = this.g_showLeftCornerTest
this.render(bgRect, 9999);
}
alignCenter(elementArray, spacing, withAni?, callback?){
let totlaWidth = 0
let length = elementArray.length
elementArray.forEach(element => {
let bd = element.ref.getBoundingBox()
totlaWidth += bd.width
});
totlaWidth += (elementArray.length-1) * spacing
let laseX = this.g_canvasWidth / 2 - totlaWidth/2;
elementArray.forEach((element, index) => {
let bd = element.ref.getBoundingBox()
if(withAni){
tweenChange(element.ref, {x: laseX + bd.width / 2}, 0.2, ()=>{
this.g_cartoon.saveSize(element.id)
if(length == (index+1)){
callback && callback()
}
})
}else{
element.ref.x = laseX + bd.width / 2
this.g_cartoon.saveSize(element.id)
if(length == (index+1)){
callback && callback()
}
}
this.renderArr = []; laseX = (laseX + bd.width + spacing)
});
}
alignLeft(elementArray, spacing, startX = 0, withAni?, callback?){
let laseX = startX;
elementArray.forEach((element, index) => {
let bd = element.ref.getBoundingBox()
if(withAni){
tweenChange(element.ref, {x: laseX + bd.width / 2}, 0.2, ()=>{
this.g_cartoon.saveSize(element.id)
if(length == (index+1)){
callback && callback()
}
})
}else{
element.ref.x = laseX + bd.width / 2
this.g_cartoon.saveSize(element.id)
if(length == (index+1)){
callback && callback()
}
}
laseX = (laseX + bd.width + spacing)
});
}
createTestLine(x, y, height, color?){
var colorAll = ['#ff0000','#eb4310','#f6941d','#fbb417','#ffff00','#cdd541','#99cc33','#3f9337','#219167','#239676','#24998d','#1f9baa','#0080ff','#3366cc','#333399','#003366','#800080','#a1488e','#c71585','#bd2158'];
color = color ? color : colorAll[Math.floor(Math.random()*20)]
this.render(this.g_cartoon.createRectangula({
width: 5,
height: height,
x: x,
y: y,
fillColor: color
}), 9999)
} }
getSuitSizeBackground(key, width){
let bgAll = multiSizeBackground[key]
if(!bgAll){
return ""
}
let suitFileName = ""
for(let fileName in bgAll){
if( Number(fileName) >= width){
suitFileName = bgAll[fileName]
break
}
}
return suitFileName
}
/**
* 初始化试图
*/
initView() {
this.initPic();
this.initBottomPart();
}
initBottomPart() {
const btnLeft = new MySprite();
btnLeft.init(this.images.get('btn_left'));
btnLeft.x = this.canvasWidth - 150 * this.mapScale;
btnLeft.y = this.canvasHeight - 100 * this.mapScale;
btnLeft.setScaleXY(this.mapScale);
this.renderArr.push(btnLeft);
this.btnLeft = btnLeft;
const btnRight = new MySprite();
btnRight.init(this.images.get('btn_right'));
btnRight.x = this.canvasWidth - 50 * this.mapScale;
btnRight.y = this.canvasHeight - 100 * this.mapScale;
btnRight.setScaleXY(this.mapScale);
this.renderArr.push(btnRight);
this.btnRight = btnRight;
}
initPic() {
const maxW = this.canvasWidth * 0.7;
const pic1 = new MySprite();
pic1.init(this.images.get(this.data.pic_url));
pic1.x = this.canvasWidth / 2;
pic1.y = this.canvasHeight / 2;
pic1.setScaleXY(maxW / pic1.width);
this.renderArr.push(pic1);
this.pic1 = pic1;
const label1 = new Label();
label1.text = this.data.text;
label1.textAlign = 'center';
label1.fontSize = 50;
label1.fontName = 'BRLNSDB';
label1.fontColor = '#ffffff';
pic1.addChild(label1);
const pic2 = new MySprite();
pic2.init(this.images.get(this.data.pic_url_2));
pic2.x = this.canvasWidth / 2 + this.canvasWidth;
pic2.y = this.canvasHeight / 2;
pic2.setScaleXY(maxW / pic2.width);
this.renderArr.push(pic2);
this.pic2 = pic2;
this.curPic = pic1;
}
btnLeftClicked() {
this.lastPage();
}
btnRightClicked() {
this.nextPage();
}
lastPage() {
if (this.curPic == this.pic1) { // --------------------------------------------------
return; // -------------- Template function ---------------
} // --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
//
// .-~~~~~~~~~-._ _.-~~~~~~~~~-.
// __.' ~. .~ `.__
// .'// \./ \\`.
// .'// | \\`.
// .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`.
// .'//.-" `-. | .-' "-.\\`.
// .'//______.============-.. \ | / ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
// --------------------------------------------------
// showParticle( element_id ) 泡泡效果
// --------------------------------------------------
// showEndPatal() / stopEndPatal() 花瓣飘落结束动画
// --------------------------------------------------
// showCorrectPatal() 指定元素上面飘花
// --------------------------------------------------
// convertPercentToRadian() 将百分比转换为弧长 第一个参数是百分比,第二个参数是方向 true为逆时针,false为顺时针。用于ShapeCircle换圆弧
// --------------------------------------------------
// movePaoWuxian() 元素抛物线跳
// --------------------------------------------------
// showJellyAnimation()------------------------------
// showBlingStar()----------------------显示星星效果--
// --------------------------------------------------
this.canTouch = false;
const moveLen = this.canvasWidth; // 泡泡
tweenChange(this.pic1, {x: this.pic1.x + moveLen}, 1); showParticle(card) {
tweenChange(this.pic2, {x: this.pic2.x + moveLen}, 1, () => { let myCard = this.g_cartoon.getCartoonElementRelativePosition(card.id)
this.canTouch = true; showPopParticle(this.g_cartoon.images.get("_bubble"), { x: myCard.x , y: myCard.y }, this.g_stage);
this.curPic = this.pic1;
});
} }
nextPage() { // 选择正确动画
showCorrectPatal(card_id, showTime, callback?) {
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = true;
this.addCorrectPetal(card_id);
setTimeout(()=>{
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = false;
callback && callback()
},showTime)
}
stopAllCorrectPatal(){
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = false;
}
if (this.curPic == this.pic2) { addCorrectPetal(card_id) {
if (!this.m_showElementPetalFlag) {
return; return;
} }
this.canTouch = false; let element = this.g_cartoon.getCartoonElement(card_id)
const petal = new MySprite(this.g_ctx);
const moveLen = this.canvasWidth;
tweenChange(this.pic1, {x: this.pic1.x - moveLen}, 1);
tweenChange(this.pic2, {x: this.pic2.x - moveLen}, 1, () => {
this.canTouch = true;
this.curPic = this.pic2;
});
}
pic1Clicked() {
this.playAudio(this.data.audio_url);
}
pic2Clicked() { const id = Math.ceil(Math.random() * 3);
this.playAudio(this.data.audio_url_2); petal.init(this.g_cartoon.images.get(this.m_PetalImage + id));
}
const randomS = (Math.random() * 0.4 + 0.6) * this.g_mapScale * 0.5;
petal.setScaleXY(randomS);
const randomR = Math.random() * 360;
petal.rotation = randomR;
const randomX = Math.random() * element.ref.width * this.g_mapScale;
petal.x = element.ref.x - (element.ref.width * this.g_mapScale / 2) + randomX;
petal.y = element.ref.y - (element.ref.height * this.g_mapScale / 2);
mapDown(event) { const randomT = 1 + Math.random() * 2;
petal["time"] = randomT;
if (!this.canTouch) { let randomTR = 360 * Math.random(); // - 180;
return; if (Math.random() < 0.5) {
randomTR *= -1;
} }
petal["tr"] = randomTR;
this.m_elementPetalArr.push(petal);
moveItem(
petal,
petal.x,
element.ref.y + (element.ref.height * this.g_mapScale / 2),
petal["time"],
() => {
removeItemFromArr(this.m_elementPetalArr, petal);
}
);
rotateItem(petal, petal["tr"], petal["time"]);
setTimeout(() => {
this.addCorrectPetal(card_id);
}, 200);
}
if ( this.checkClickTarget(this.btnLeft) ) {
this.btnLeftClicked();
return;
}
if ( this.checkClickTarget(this.btnRight) ) { // 结束动画花瓣飘落
this.btnRightClicked(); showEndPatal() {
return; this.m_endPageArr = [];
} this.m_showPetalFlag = true;
this.addPetal();
}
if ( this.checkClickTarget(this.pic1) ) { stopEndPatal() {
this.pic1Clicked(); this.m_endPageArr = [];
return; this.m_showPetalFlag = false;
} }
if ( this.checkClickTarget(this.pic2) ) { addPetal() {
this.pic2Clicked(); if (!this.m_showPetalFlag) {
return; return;
} }
const petal = this.getPetal();
} this.m_endPageArr.push(petal);
moveItem(
mapMove(event) { petal,
petal.x,
this.g_canvasHeight + petal.height * petal.scaleY,
petal["time"],
() => {
removeItemFromArr(this.m_endPageArr, petal);
}
);
rotateItem(petal, petal["tr"], petal["time"]);
setTimeout(() => {
this.addPetal();
}, 100);
} }
mapUp(event) { getPetal() {
const petal = new MySprite(this.g_ctx);
} const id = Math.ceil(Math.random() * 3);
petal.init(this.g_cartoon.images.get(this.m_PetalImage + id));
const randomS = (Math.random() * 0.4 + 0.6) * this.g_mapScale;
petal.setScaleXY(randomS);
const randomR = Math.random() * 360;
petal.rotation = randomR;
update() { const randomX = Math.random() * this.g_canvasWidth;
petal.x = randomX;
petal.y = (-petal.height / 2) * petal.scaleY;
// ---------------------------------------------------------- const randomT = 2 + Math.random() * 5;
this.animationId = window.requestAnimationFrame(this.update.bind(this)); petal["time"] = randomT;
// 清除画布内容
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
// tween 更新动画
TWEEN.update();
// ----------------------------------------------------------
let randomTR = 360 * Math.random(); // - 180;
if (Math.random() < 0.5) {
randomTR *= -1;
}
petal["tr"] = randomTR;
return petal;
}
this.updateArr(this.renderArr);
showJellyAnimation(element_id, callback?){
let element = this.g_cartoon.getCartoonElement(element_id).ref
tweenChange(element,{ scaleX: element.initScaleX * 1.2 , scaleY: element.initScaleY * 1.1 }, 0.1, ()=>{
tweenChange(element,{ scaleX: element.initScaleX * 0.8 , scaleY: element.initScaleY * 0.9 }, 0.1, ()=>{
tweenChange(element,{ scaleX: element.initScaleX , scaleY: element.initScaleY }, 0.1, ()=>{
callback && callback()
})
})
})
}
showShakeAnimation(element_id, callback?){
let element = this.g_cartoon.getCartoonElement(element_id).ref
let originX = element.x
tweenChange(element,{ x: originX - 10*this.g_mapScale }, 0.1, ()=>{
tweenChange(element,{ x: originX + 10*this.g_mapScale }, 0.1, ()=>{
tweenChange(element,{ x: originX }, 0.1, ()=>{
callback && callback()
})
})
})
} }
convertPercentToRadian(per, direction){
let radian = 0;
if(direction) { //逆时针
if(per*360 > 270){
radian = 361 - (per*360 - 270)
}else{
radian = 270 - per*360
}
}else{ //顺时针
if(per*360 > 90){
radian = per*360 - 90
}else{
radian = 270 + per*360
}
}
return (radian * Math.PI) / 180;
}
showBlingStar(element, callback?){
let rect = element.getBoundingBox()
showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 0.5);
this.m_setTimeoutIDs.push(setTimeout(() => {
callback && callback()
}, 2000))
// setTimeout(()=>{
// showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 1.8);
// },200)
// setTimeout(()=>{
// showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 1.6);
// },400)
}
movePaoWuxian(element,dis,time,callback?){
let disX = dis.x - element.x
let disY = (element.y - dis.y)
let count = 0
let runTime = time/5
let vx = disX/runTime
let a = -0.05
let vy0 = disY/runTime - 0.5*a*runTime
let id = setInterval(()=>{
element.x += vx
element.y -= vy0 + a*count
count++;
if(count>runTime){
clearInterval(id)
callback && callback()
}
}, 5);
}
} }
const res = [ const localImages = {
'_bg_1280_720_Ruler': 'assets/play/default/images/1280_720_Ruler.png',
'_mask_layer_1280_720': 'assets/play/default/images/mask_layer_1280_720.png',
'_bg_240_180': 'assets/play/default/images/bg_240_180.png',
'_bg_453_251': 'assets/play/default/images/bg_453_251.png',
'_bg_1280_222': 'assets/play/default/images/bg_1280_222.png',
'_bg_1280_720': 'assets/play/default/images/bg_1280_720.png',
'_bg_200_200': 'assets/play/default/images/bg_200_200.png',
'_bg_30_30': 'assets/play/default/images/bg_30_30.png',
'_bg_500_600': 'assets/play/default/images/bg_500_600.png',
'_bg_50_50': 'assets/play/default/images/bg_50_50.png',
'_bg_75_50': 'assets/play/default/images/bg_75_50.png',
'_bg_75_50_black': 'assets/play/default/images/bg_75_50_black.png',
'_flag': 'assets/play/default/images/flag.png',
'_go': 'assets/play/default/images/go.png',
'_header': 'assets/play/default/images/header.png',
'_ready': 'assets/play/default/images/ready.png',
'_replay': 'assets/play/default/images/replay.png',
'_scrap-pic-1': 'assets/play/default/images/scrap-pic-1.png',
'_scrap-pic-2': 'assets/play/default/images/scrap-pic-2.png',
'_scrap-pic-3': 'assets/play/default/images/scrap-pic-3.png',
'_sm-pic-1': 'assets/play/default/images/sm-pic-1.png',
'_sm-pic-2': 'assets/play/default/images/sm-pic-2.png',
'_sm-pic-3': 'assets/play/default/images/sm-pic-3.png',
'_sm-pic-4': 'assets/play/default/images/sm-pic-4.png',
'_star': 'assets/play/default/images/star.png',
'_bubble': 'assets/play/default/images/bubble.png',
'_image_none': 'assets/play/default/images/image_none.png',
// ['bg', "assets/play/bg.jpg"], 'background': 'assets/play/background.png',
['btn_left', "assets/play/btn_left.png"], 'blue': 'assets/play/blue.png',
['btn_right', "assets/play/btn_right.png"], 'boy_1': 'assets/play/boy_1.png',
// ['text_bg', "assets/play/text_bg.png"], 'btn_start': 'assets/play/btn_start.png',
'card_bg': 'assets/play/card_bg.png',
'creatJsonProfile': 'assets/play/creatJsonProfile.py',
'dengqiu1': 'assets/play/dengqiu1.png',
'filename': 'assets/play/filename.txt',
'green': 'assets/play/green.png',
'hand': 'assets/play/hand.png',
'hand2': 'assets/play/hand2.png',
'hengban': 'assets/play/hengban.png',
'huaban': 'assets/play/huaban.png',
'lianzi0': 'assets/play/lianzi0.png',
'lianzi3': 'assets/play/lianzi3.png',
'lianzi4': 'assets/play/lianzi4.png',
'lianzil': 'assets/play/lianzil.png',
'lianzir': 'assets/play/lianzir.png',
'light1': 'assets/play/light1.png',
'light2': 'assets/play/light2.png',
'light3': 'assets/play/light3.png',
'light4': 'assets/play/light4.png',
'qiaoji1': 'assets/play/qiaoji1.png',
'red': 'assets/play/red.png',
'resizeImg': 'assets/play/resizeImg.py',
'restart': 'assets/play/restart.png',
'star': 'assets/play/star.png',
'yellow': 'assets/play/yellow.png',
]; 'boy (1)': 'assets/play/frame/boy (1).png',
'boy (10)': 'assets/play/frame/boy (10).png',
'boy (11)': 'assets/play/frame/boy (11).png',
'boy (12)': 'assets/play/frame/boy (12).png',
'boy (13)': 'assets/play/frame/boy (13).png',
'boy (14)': 'assets/play/frame/boy (14).png',
'boy (15)': 'assets/play/frame/boy (15).png',
'boy (16)': 'assets/play/frame/boy (16).png',
'boy (17)': 'assets/play/frame/boy (17).png',
'boy (18)': 'assets/play/frame/boy (18).png',
'boy (19)': 'assets/play/frame/boy (19).png',
'boy (2)': 'assets/play/frame/boy (2).png',
'boy (20)': 'assets/play/frame/boy (20).png',
'boy (21)': 'assets/play/frame/boy (21).png',
'boy (22)': 'assets/play/frame/boy (22).png',
'boy (23)': 'assets/play/frame/boy (23).png',
'boy (24)': 'assets/play/frame/boy (24).png',
'boy (25)': 'assets/play/frame/boy (25).png',
'boy (26)': 'assets/play/frame/boy (26).png',
'boy (27)': 'assets/play/frame/boy (27).png',
'boy (28)': 'assets/play/frame/boy (28).png',
'boy (29)': 'assets/play/frame/boy (29).png',
'boy (3)': 'assets/play/frame/boy (3).png',
'boy (30)': 'assets/play/frame/boy (30).png',
'boy (4)': 'assets/play/frame/boy (4).png',
'boy (5)': 'assets/play/frame/boy (5).png',
'boy (6)': 'assets/play/frame/boy (6).png',
'boy (7)': 'assets/play/frame/boy (7).png',
'boy (8)': 'assets/play/frame/boy (8).png',
'boy (9)': 'assets/play/frame/boy (9).png',
};
const localAudios = {
'sm-back': "assets/play/default/audio/sm-back.mp3",
'sm-display': "assets/play/default/audio/sm-display.mp3",
'sm-wrong': "assets/play/default/audio/sm-wrong.mp3",
'sm-win': "assets/play/default/audio/sm-win.mp3",
'sm-in': "assets/play/default/audio/sm-in.mp3",
'sm-out': "assets/play/default/audio/sm-out.mp3",
'sm-click': "assets/play/default/audio/sm-click.mp3",
'sm-start': "assets/play/default/audio/sm-start.mp3",
'sm-correct': 'assets/play/default/audio/sm-correct.mp3',
'sm-star': "assets/play/default/audio/sm-star.mp3",
'sm-choice-complete': 'assets/play/default/audio/sm-choice-complete.mp3',
'sm-choice-correct': 'assets/play/default/audio/sm-choice-correct.mp3',
'sm-choice-error': 'assets/play/default/audio/sm-choice-error.mp3',
'sm-choice-in': 'assets/play/default/audio/sm-choice-in.mp3',
'sm-choice-show-answer': 'assets/play/default/audio/sm-choice-show-answer.mp3',
'sm-choice-timeup-0': 'assets/play/default/audio/sm-choice-timeup-0.mp3',
'sm-choice-timeup-3': 'assets/play/default/audio/sm-choice-timeup-3.mp3',
'sm-go': 'assets/play/default/audio/sm-go.mp3',
'sm-ready': 'assets/play/default/audio/sm-ready.mp3',
const resAudio = [ 'dianji': 'assets/play/sound/dianji.mp3',
'gusheng_1': 'assets/play/sound/gusheng_1.mp3',
'gusheng_2': 'assets/play/sound/gusheng_2.mp3',
'gusheng_3': 'assets/play/sound/gusheng_3.mp3',
'gusheng_4': 'assets/play/sound/gusheng_4.mp3',
'gusheng_kaitou': 'assets/play/sound/gusheng_kaitou.mp3',
'guzhang': 'assets/play/sound/guzhang.mp3',
'jiazigu_changgusheng': 'assets/play/sound/jiazigu_changgusheng.mp3',
'tongshenghuanhu': 'assets/play/sound/tongshenghuanhu.mp3',
};
['click', "assets/play/music/click.mp3"], const multiSizeBackground = {
]; }
export {localImages, localAudios, multiSizeBackground};
export {res, resAudio};
@mixin hide-overflow-text {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
@mixin k-no-select {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
@mixin k-img-bg {
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
.anticon{
vertical-align: .1em!important;
}
import os
import json
def file_name(file_dir):
fileList =["bg_kuang", "bg_kuang2", "bg_light"]
f = open('filename.txt', 'w');
blank = False
for root, dirs, files in os.walk(file_dir):
for fileName in files:
if root.split("\\")[-1]=="frame" or root.split("\\")[-1]=="sound" or root.split("\\")[-1]=="play" or (root.split("\\")[-1] in fileList):
blank = True
if root.split("\\")[-1] != "play":
f.write("'" + fileName.split(".")[0] + "': 'assets/play/" + root.split("\\")[-1] + "/" + fileName + "',\n")
else:
f.write("'" + fileName.split(".")[0] + "': 'assets/" + root.split("\\")[-1] + "/" + fileName + "',\n")
if blank:
f.write("\n")
blank = False
f.close()
fileList = file_name(os.path.abspath('.'))
export default {
version: "1.0",
key: "DataKey_East_L226",
dataArray: [],
}
\ No newline at end of file
'background': 'assets/play/background.png',
'blue': 'assets/play/blue.png',
'boy_1': 'assets/play/boy_1.png',
'btn_start': 'assets/play/btn_start.png',
'card_bg': 'assets/play/card_bg.png',
'creatJsonProfile': 'assets/play/creatJsonProfile.py',
'dengqiu1': 'assets/play/dengqiu1.png',
'filename': 'assets/play/filename.txt',
'green': 'assets/play/green.png',
'hand': 'assets/play/hand.png',
'hand2': 'assets/play/hand2.png',
'hengban': 'assets/play/hengban.png',
'huaban': 'assets/play/huaban.png',
'lianzi0': 'assets/play/lianzi0.png',
'lianzi3': 'assets/play/lianzi3.png',
'lianzi4': 'assets/play/lianzi4.png',
'lianzil': 'assets/play/lianzil.png',
'lianzir': 'assets/play/lianzir.png',
'light1': 'assets/play/light1.png',
'light2': 'assets/play/light2.png',
'light3': 'assets/play/light3.png',
'light4': 'assets/play/light4.png',
'qiaoji1': 'assets/play/qiaoji1.png',
'red': 'assets/play/red.png',
'resizeImg': 'assets/play/resizeImg.py',
'restart': 'assets/play/restart.png',
'star': 'assets/play/star.png',
'yellow': 'assets/play/yellow.png',
'boy (1)': 'assets/play/frame/boy (1).png',
'boy (10)': 'assets/play/frame/boy (10).png',
'boy (11)': 'assets/play/frame/boy (11).png',
'boy (12)': 'assets/play/frame/boy (12).png',
'boy (13)': 'assets/play/frame/boy (13).png',
'boy (14)': 'assets/play/frame/boy (14).png',
'boy (15)': 'assets/play/frame/boy (15).png',
'boy (16)': 'assets/play/frame/boy (16).png',
'boy (17)': 'assets/play/frame/boy (17).png',
'boy (18)': 'assets/play/frame/boy (18).png',
'boy (19)': 'assets/play/frame/boy (19).png',
'boy (2)': 'assets/play/frame/boy (2).png',
'boy (20)': 'assets/play/frame/boy (20).png',
'boy (21)': 'assets/play/frame/boy (21).png',
'boy (22)': 'assets/play/frame/boy (22).png',
'boy (23)': 'assets/play/frame/boy (23).png',
'boy (24)': 'assets/play/frame/boy (24).png',
'boy (25)': 'assets/play/frame/boy (25).png',
'boy (26)': 'assets/play/frame/boy (26).png',
'boy (27)': 'assets/play/frame/boy (27).png',
'boy (28)': 'assets/play/frame/boy (28).png',
'boy (29)': 'assets/play/frame/boy (29).png',
'boy (3)': 'assets/play/frame/boy (3).png',
'boy (30)': 'assets/play/frame/boy (30).png',
'boy (4)': 'assets/play/frame/boy (4).png',
'boy (5)': 'assets/play/frame/boy (5).png',
'boy (6)': 'assets/play/frame/boy (6).png',
'boy (7)': 'assets/play/frame/boy (7).png',
'boy (8)': 'assets/play/frame/boy (8).png',
'boy (9)': 'assets/play/frame/boy (9).png',
'dianji': 'assets/play/sound/dianji.mp3',
'gusheng_1': 'assets/play/sound/gusheng_1.mp3',
'gusheng_2': 'assets/play/sound/gusheng_2.mp3',
'gusheng_3': 'assets/play/sound/gusheng_3.mp3',
'gusheng_4': 'assets/play/sound/gusheng_4.mp3',
'gusheng_kaitou': 'assets/play/sound/gusheng_kaitou.mp3',
'guzhang': 'assets/play/sound/guzhang.mp3',
'jiazigu_changgusheng': 'assets/play/sound/jiazigu_changgusheng.mp3',
'tongshenghuanhu': 'assets/play/sound/tongshenghuanhu.mp3',
...@@ -36,7 +36,7 @@ ...@@ -36,7 +36,7 @@
} }
importScripts('assets/libs/audio-recorder/lame.min.js'); importScripts('assets/play/libs/audio-recorder/lame.min.js');
var mp3Encoder, maxSamples = 1152, samplesMono, lame, config, dataBuffer; var mp3Encoder, maxSamples = 1152, samplesMono, lame, config, dataBuffer;
......
!function(){"use strict";function r(r){r||(r=Math.random),this.p=e(r),this.perm=new Uint8Array(512),this.permMod12=new Uint8Array(512);for(var t=0;t<512;t++)this.perm[t]=this.p[255&t],this.permMod12[t]=this.perm[t]%12}function e(r){var e,t=new Uint8Array(256);for(e=0;e<256;e++)t[e]=e;for(e=0;e<255;e++){var a=e+1+~~(r()*(255-e)),i=t[e];t[e]=t[a],t[a]=i}return t}var t=.5*(Math.sqrt(3)-1),a=(3-Math.sqrt(3))/6,i=1/3,o=1/6,n=(Math.sqrt(5)-1)/4,f=(5-Math.sqrt(5))/20;r.prototype={grad3:new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),grad4:new Float32Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]),noise2D:function(r,e){var i,o,n=this.permMod12,f=this.perm,s=this.grad3,v=0,h=0,d=0,l=(r+e)*t,p=Math.floor(r+l),u=Math.floor(e+l),M=(p+u)*a,m=p-M,y=u-M,w=r-m,c=e-y;w>c?(i=1,o=0):(i=0,o=1);var g=w-i+a,x=c-o+a,A=w-1+2*a,q=c-1+2*a,D=255&p,U=255&u,b=.5-w*w-c*c;if(b>=0){var F=3*n[D+f[U]];b*=b,v=b*b*(s[F]*w+s[F+1]*c)}var N=.5-g*g-x*x;if(N>=0){var S=3*n[D+i+f[U+o]];N*=N,h=N*N*(s[S]*g+s[S+1]*x)}var P=.5-A*A-q*q;if(P>=0){var T=3*n[D+1+f[U+1]];P*=P,d=P*P*(s[T]*A+s[T+1]*q)}return 70*(v+h+d)},noise3D:function(r,e,t){var a,n,f,s,v,h,d,l,p,u,M=this.permMod12,m=this.perm,y=this.grad3,w=(r+e+t)*i,c=Math.floor(r+w),g=Math.floor(e+w),x=Math.floor(t+w),A=(c+g+x)*o,q=c-A,D=g-A,U=x-A,b=r-q,F=e-D,N=t-U;b>=F?F>=N?(v=1,h=0,d=0,l=1,p=1,u=0):b>=N?(v=1,h=0,d=0,l=1,p=0,u=1):(v=0,h=0,d=1,l=1,p=0,u=1):F<N?(v=0,h=0,d=1,l=0,p=1,u=1):b<N?(v=0,h=1,d=0,l=0,p=1,u=1):(v=0,h=1,d=0,l=1,p=1,u=0);var S=b-v+o,P=F-h+o,T=N-d+o,_=b-l+2*o,j=F-p+2*o,k=N-u+2*o,z=b-1+3*o,B=F-1+3*o,C=N-1+3*o,E=255&c,G=255&g,H=255&x,I=.6-b*b-F*F-N*N;if(I<0)a=0;else{var J=3*M[E+m[G+m[H]]];I*=I,a=I*I*(y[J]*b+y[J+1]*F+y[J+2]*N)}var K=.6-S*S-P*P-T*T;if(K<0)n=0;else{var L=3*M[E+v+m[G+h+m[H+d]]];K*=K,n=K*K*(y[L]*S+y[L+1]*P+y[L+2]*T)}var O=.6-_*_-j*j-k*k;if(O<0)f=0;else{var Q=3*M[E+l+m[G+p+m[H+u]]];O*=O,f=O*O*(y[Q]*_+y[Q+1]*j+y[Q+2]*k)}var R=.6-z*z-B*B-C*C;if(R<0)s=0;else{var V=3*M[E+1+m[G+1+m[H+1]]];R*=R,s=R*R*(y[V]*z+y[V+1]*B+y[V+2]*C)}return 32*(a+n+f+s)},noise4D:function(r,e,t,a){var i,o,s,v,h,d=(this.permMod12,this.perm),l=this.grad4,p=(r+e+t+a)*n,u=Math.floor(r+p),M=Math.floor(e+p),m=Math.floor(t+p),y=Math.floor(a+p),w=(u+M+m+y)*f,c=u-w,g=M-w,x=m-w,A=y-w,q=r-c,D=e-g,U=t-x,b=a-A,F=0,N=0,S=0,P=0;q>D?F++:N++,q>U?F++:S++,q>b?F++:P++,D>U?N++:S++,D>b?N++:P++,U>b?S++:P++;var T,_,j,k,z,B,C,E,G,H,I,J;T=F>=3?1:0,_=N>=3?1:0,j=S>=3?1:0,k=P>=3?1:0,z=F>=2?1:0,B=N>=2?1:0,C=S>=2?1:0,E=P>=2?1:0,G=F>=1?1:0,H=N>=1?1:0,I=S>=1?1:0,J=P>=1?1:0;var K=q-T+f,L=D-_+f,O=U-j+f,Q=b-k+f,R=q-z+2*f,V=D-B+2*f,W=U-C+2*f,X=b-E+2*f,Y=q-G+3*f,Z=D-H+3*f,$=U-I+3*f,rr=b-J+3*f,er=q-1+4*f,tr=D-1+4*f,ar=U-1+4*f,ir=b-1+4*f,or=255&u,nr=255&M,fr=255&m,sr=255&y,vr=.6-q*q-D*D-U*U-b*b;if(vr<0)i=0;else{var hr=d[or+d[nr+d[fr+d[sr]]]]%32*4;vr*=vr,i=vr*vr*(l[hr]*q+l[hr+1]*D+l[hr+2]*U+l[hr+3]*b)}var dr=.6-K*K-L*L-O*O-Q*Q;if(dr<0)o=0;else{var lr=d[or+T+d[nr+_+d[fr+j+d[sr+k]]]]%32*4;dr*=dr,o=dr*dr*(l[lr]*K+l[lr+1]*L+l[lr+2]*O+l[lr+3]*Q)}var pr=.6-R*R-V*V-W*W-X*X;if(pr<0)s=0;else{var ur=d[or+z+d[nr+B+d[fr+C+d[sr+E]]]]%32*4;pr*=pr,s=pr*pr*(l[ur]*R+l[ur+1]*V+l[ur+2]*W+l[ur+3]*X)}var Mr=.6-Y*Y-Z*Z-$*$-rr*rr;if(Mr<0)v=0;else{var mr=d[or+G+d[nr+H+d[fr+I+d[sr+J]]]]%32*4;Mr*=Mr,v=Mr*Mr*(l[mr]*Y+l[mr+1]*Z+l[mr+2]*$+l[mr+3]*rr)}var yr=.6-er*er-tr*tr-ar*ar-ir*ir;if(yr<0)h=0;else{var wr=d[or+1+d[nr+1+d[fr+1+d[sr+1]]]]%32*4;yr*=yr,h=yr*yr*(l[wr]*er+l[wr+1]*tr+l[wr+2]*ar+l[wr+3]*ir)}return 27*(i+o+s+v+h)}},r._buildPermutationTable=e,"undefined"!=typeof define&&define.amd&&define(function(){return r}),"undefined"!=typeof exports?exports.SimplexNoise=r:"undefined"!=typeof window&&(window.SimplexNoise=r),"undefined"!=typeof module&&(module.exports=r)}();
//# sourceMappingURL=simplex-noise.min.js.map
\ No newline at end of file
import os
import shutil
from PIL import Image
fileName = os.listdir('./')
withBorder = False
border_left = ""
border_right = ""
imageName = input("图片名:")
if input("是否包含边框? (y/n):")=="y":
withBorder = True
if withBorder:
border_left = input("左边框文件名:")
border_right = input("右边框文件名:")
number = int(input("数量:"))
if os.path.exists('./' + imageName + '/'):
shutil.rmtree('./' + imageName + '/')
os.mkdir('./' + imageName + '/')
pic = Image.open('./' + imageName + '.PNG')
width = pic.width
height = pic.height
f = open('./' + imageName + '/' + imageName + '_map.txt', 'w')
if withBorder:
borderImg_left, borderImg_right = Image.open('./' + border_left + '.PNG'), Image.open('./' + border_right + '.PNG')
for index in range(1, number):
newpic = pic.resize((width*index, height),Image.ANTIALIAS)
loc1, loc2, loc3 = (0, 0), (borderImg_left.width, 0), (borderImg_left.width +newpic.width, 0)
join_pic = Image.new('RGBA', (borderImg_left.width + newpic.width + borderImg_right.width, newpic.height))
join_pic.paste(borderImg_left, loc1)
join_pic.paste(newpic, loc2)
join_pic.paste(borderImg_right, loc3)
join_pic.save('./' + imageName + '/' + imageName + '_' + str(index) + 'x.PNG')
f.write('"' + str(width*index) + '": "' + imageName + '_' + str(index) + 'x",\n')
f.close()
else:
for index in range(1, number):
newpic = pic.resize((width*index, height),Image.ANTIALIAS)
newpic.save('./' + imageName + '/' + imageName + '_' + str(index) + 'x.PNG')
f.write('"' + str(width*index) + '": "' + imageName + '_' + str(index) + 'x",\n')
f.close()
\ No newline at end of file
<!doctype html> <!DOCTYPE html>
<html lang="en"> <html lang="zh">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8" />
<title>NgOne</title> <title>NgOne</title>
<base href="/"> <base href="/" />
<!-- <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">--> <style>
<meta name="viewport" content="width=device-width, initial-scale=1"> html, body{
<link rel="icon" type="image/x-icon" href="favicon.ico"> width: 100%;
<script type="text/javascript" src="https://staging-teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air.js"></script> height: 100%;
</head> }
<body> </style>
<app-root></app-root> <meta name="viewport" content="width=device-width, initial-scale=1" />
</body> <link rel="icon" type="image/x-icon" href="favicon.ico" />
<!-- <script type="text/javascript" src="http://teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air.js" ></script> -->
<script type="text/javascript" src="https://staging-teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air_online.js"></script>
</head>
<body>
<app-root></app-root>
</body>
</html> </html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NgOne</title>
<base href="/">
<!-- <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script type="text/javascript" src="https://staging-teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air.js"></script>
</head>
<body>
Hello World!!
</body>
</html>
/* You can add global styles to this file, and also import other style files */ /* You can add global styles to this file, and also import other style files */
@import "~ng-zorro-antd/src/ng-zorro-antd.css";
\ No newline at end of file
...@@ -2,9 +2,7 @@ ...@@ -2,9 +2,7 @@
"extends": "./tsconfig.json", "extends": "./tsconfig.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./out-tsc/app", "outDir": "./out-tsc/app",
"types": [ "types": []
"node"
]
}, },
"files": [ "files": [
"src/main.ts", "src/main.ts",
......
This source diff could not be displayed because it is too large. You can view the blob instead.
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