Commit 8fa94689 authored by 李维's avatar 李维

dev commit

parent 7b9a904b
# ng-template-generator
angularjs技术框架下的H5互动模板框架脚手架,基于NG-ZORRO实现快速开发基于绘玩云的H5互动课件。
# 使用简介
## 前期准备
* 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
angularjs技术框架下的H5互动模板框架脚手架
\ No newline at end of file
......@@ -3,9 +3,13 @@
"version": 1,
"newProjectRoot": "projects",
"projects": {
"ng-template-generator": {
"ng-one": {
"projectType": "application",
"schematics": {},
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
......@@ -13,26 +17,39 @@
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ng-template-generator",
"outputPath": "dist",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": true,
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets",
{ "glob": "**/*", "input": "src/assets/libs/service-worker/", "output": "/" },
{
"glob": "**/*",
"input": "./node_modules/@ant-design/icons-angular/src/inline-svg/",
"output": "/assets/"
},
{
"glob": "**/*",
"input": "./dist/game/",
"output": "/assets/cocos/"
}
],
"styles": [
"src/styles.scss",
"./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/libs/audio-recorder/lame.min.js",
"src/assets/libs/audio-recorder/worker.js",
"src/assets/libs/audio-recorder/recorder.js"
]
},
"configurations": {
"production": {
......@@ -47,39 +64,28 @@
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
"buildOptimizer": true
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "ng-template-generator:build"
"browserTarget": "ng-one:build"
},
"configurations": {
"production": {
"browserTarget": "ng-template-generator:build:production"
"browserTarget": "ng-one:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "ng-template-generator:build"
"browserTarget": "ng-one:build"
}
},
"test": {
......@@ -94,8 +100,7 @@
"src/assets"
],
"styles": [
"./node_modules/ng-zorro-antd/ng-zorro-antd.min.css",
"src/styles.css"
"src/styles.scss"
],
"scripts": []
}
......@@ -117,16 +122,15 @@
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "ng-template-generator:serve"
"devServerTarget": "ng-one:serve"
},
"configurations": {
"production": {
"devServerTarget": "ng-template-generator:serve:production"
"devServerTarget": "ng-one:serve:production"
}
}
}
}
}
},
"defaultProject": "ng-template-generator"
}},
"defaultProject": "ng-one"
}
\ No newline at end of file
......@@ -66,7 +66,7 @@ const runSpawn = async function (){
ls.on('close', (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 zipname = pkg.name+"_"+date.Format("yyyyMMdd hh-mm-ss");
......@@ -112,3 +112,4 @@ 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,76 @@
"name": "ng-template-generator",
"version": "0.0.1",
"scripts": {
"start": "ng serve",
"start": "ng serve --host=0.0.0.0",
"build": "ng build --build--optimizer --aot --base-href /JGT/v3/",
"publish": "node ./bin/publish.js",
"ng": "ng",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
"publish": "node ./bin/publish.js"
},
"private": true,
"dependencies": {
"@angular/animations": "~9.0.2",
"@angular/common": "~9.0.2",
"@angular/compiler": "~9.0.2",
"@angular/core": "~9.0.2",
"@angular/forms": "~9.0.2",
"@angular/platform-browser": "~9.0.2",
"@angular/platform-browser-dynamic": "~9.0.2",
"@angular/router": "~9.0.2",
"@fortawesome/angular-fontawesome": "^0.6.0",
"@fortawesome/fontawesome-svg-core": "^1.2.27",
"@fortawesome/free-regular-svg-icons": "^5.12.1",
"@fortawesome/free-solid-svg-icons": "^5.12.1",
"@tweenjs/tween.js": "^18.5.0",
"ali-oss": "^6.5.1",
"compressing": "^1.5.0",
"ng-zorro-antd": "^8.5.2",
"rxjs": "~6.5.4",
"@angular/animations": "^7.2.10",
"@angular/cdk": "^7.2.2",
"@angular/common": "^7.2.10",
"@angular/compiler": "^7.2.10",
"@angular/core": "^7.2.10",
"@angular/flex-layout": "^7.0.0-beta.24",
"@angular/forms": "^7.2.10",
"@angular/http": "^7.2.10",
"@angular/material": "^7.2.2",
"@angular/platform-browser": "^7.2.10",
"@angular/platform-browser-dynamic": "^7.2.10",
"@angular/platform-server": "^7.2.10",
"@angular/router": "^7.2.10",
"@tweenjs/tween.js": "^17.3.0",
"ali-oss": "^6.0.0",
"angular-bootstrap-colorpicker": "^3.0.32",
"angular-cropperjs": "^1.0.1",
"angular2-draggable": "^2.1.9",
"angular2-fontawesome": "^5.2.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",
"npm": "^6.5.0",
"rxjs": "^6.3.3",
"rxjs-compat": "^6.3.3",
"rxjs-tslint": "^0.1.6",
"spark-md5": "^3.0.0",
"tslib": "^1.10.0",
"zone.js": "~0.10.2"
"webpack": "^4.28.2",
"zone.js": "^0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.900.3",
"@angular/cli": "~9.0.3",
"@angular/compiler-cli": "~9.0.2",
"@angular/language-service": "~9.0.2",
"@types/jasmine": "~3.5.0",
"@angular-devkit/build-angular": "^0.11.4",
"@angular/cli": "^7.2.10",
"@angular/compiler-cli": "^7.2.10",
"@angular/language-service": "^7.2.10",
"@types/jasmine": "^3.3.5",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.11.1",
"codelyzer": "^5.1.2",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~2.1.0",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.2",
"protractor": "~5.4.3",
"ts-node": "~8.3.0",
"tslint": "~5.18.0",
"typescript": "~3.7.5"
"@types/node": "^10.12.18",
"codelyzer": "^4.5.0",
"jasmine-core": "^3.3.0",
"jasmine-spec-reporter": "^4.2.1",
"karma": "^3.1.4",
"karma-chrome-launcher": "^2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.0",
"karma-jasmine": "^2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "^5.4.2",
"ts-node": "~5.0.1",
"tslint": "^5.12.0",
"typescript": "3.1.1"
}
}
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';
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
export class AppComponent implements OnInit{
type = 'play';
constructor() {
const tp = this.getQueryString('type');
if (tp) {
let tp = this.getQueryString("type");
if (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 { NgZorroAntdModule, NZ_I18N, zh_CN } from 'ng-zorro-antd';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
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 zh from '@angular/common/locales/zh';
import {FormComponent} from './form/form.component';
import {PlayComponent} from './play/play.component';
import {LessonTitleConfigComponent} from './common/lesson-title-config/lesson-title-config.component';
import {BackgroundImagePipe} from './pipes/background-image.pipe';
import {UploadImageWithPreviewComponent} from './common/upload-image-with-preview/upload-image-with-preview.component';
import {PlayerContentWrapperComponent} from './common/player-content-wrapper/player-content-wrapper.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';
import {UploadImageWithPreviewComponent} from "./common/upload-image-with-preview/upload-image-with-preview.component";
import {BackgroundImagePipe} from "./pipes/background-image.pipe";
import {UploadVideoComponent} from "./common/upload-video/upload-video.component";
import {ResourcePipe} from "./pipes/resource.pipe";
import {TimePipe} from "./pipes/time.pipe";
import {CustomHotZoneComponent} from "./common/custom-hot-zone/custom-hot-zone.component";
registerLocaleData(zh);
@NgModule({
......@@ -40,26 +41,22 @@ registerLocaleData(zh);
TimePipe,
UploadVideoComponent,
CustomHotZoneComponent,
PlayerContentWrapperComponent
],
imports: [
BrowserModule,
NgZorroAntdModule,
FormsModule,
HttpClientModule,
BrowserAnimationsModule,
FontAwesomeModule
BrowserModule,
Angular2FontawesomeModule,
NgZorroAntdModule,
//ColorPickerModule
],
providers: [
{provide: ErrorHandler, useClass: MyErrorHandler},
/** 配置 ng-zorro-antd 国际化(文案 及 日期) **/
providers : [
{ provide: NZ_I18N, useValue: zh_CN }
],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(library: FaIconLibrary) {
library.addIconPacks(fas, far);
}
}
export class AppModule { }
<div class="d-flex">
<div class="p-btn-record d-flex">
<div class="btn-clear" style="cursor: pointer" (click)="onBtnClearAudio()" *ngIf="withRmBtn && (audioUrl || audioBlob)">
<fa-icon icon="times"></fa-icon>
<div
class="btn-clear"
(click)="onBtnClearAudio()"
*ngIf="withRmBtn && (audioUrl || audioBlob)"
>
<fa name="close"></fa>
</div>
<div class="btn-record" *ngIf="type===Type.RECORD && !isUploading"
<div
class="btn-record"
*ngIf="type === Type.RECORD && !isUploading"
[class.p-recording]="isRecording"
(click)="onBtnRecord()">
<fa-icon icon="microphone"></fa-icon>
(click)="onBtnRecord()"
>
<i nz-icon nzType="audio" nzTheme="outline"></i>
Record Audio
</div>
<nz-upload
[nzAccept] = "'.mp3'"
[nzAccept]="'.mp3'"
[nzShowUploadList]="false"
[nzAction]="uploadUrl"
[nzData]="uploadData"
(nzChange)="handleChange($event)">
<div class="btn-upload" [ngClass]="{'has-clear': withRmBtn && (audioUrl || audioBlob)}" *ngIf="type===Type.UPLOAD && !isUploading">
<fa-icon icon="upload"></fa-icon>
(nzChange)="handleChange($event)"
>
<div
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
</div>
</nz-upload>
<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">
<fa-icon icon="cloud-upload-alt"></fa-icon>
<i nz-icon nzType="loading" nzTheme="outline"></i>
Uploading...
</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()">
<fa-icon icon="close"></fa-icon>
<i nz-icon nzType="close" nzTheme="outline"></i>
</div>
</ng-template>
<ng-template #falsyTemplate>
<div class="btn-switch" (click)="onBtnSwitchType()">
<fa-icon icon="cog"></fa-icon>
<i nz-icon nzType="setting" nzTheme="outline"></i>
</div>
</ng-template>
</div>
<div class="p-progress ml-2" (click)="onBtnPlay()" *ngIf="audioUrl || audioBlob">
<nz-progress [nzPercent]="percent" [nzWidth]="30" [nzFormat]="progressText"
nzType="circle"></nz-progress>
<div class="p-btn-play" [style.left]="isPlaying?'8px':''">
<fa-icon [icon]="playIcon"></fa-icon>
<div
class="p-progress ml-2"
(click)="onBtnPlay()"
*ngIf="audioUrl || audioBlob"
>
<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>
.d-flex{
display: flex;
}
.p-btn-record {
font-size: 0.9rem;
color: #555;
......@@ -91,6 +88,7 @@
.p-progress {
margin-top: 2px;
margin-left: 5px;
position: relative;
line-height: 26px;
.p-btn-play {
......@@ -105,3 +103,6 @@
line-height: 33px;
}
.d-flex{
display: flex;
}
\ No newline at end of file
......@@ -19,11 +19,10 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
isUploading = false;
type = Type.UPLOAD; // record | upload
Type = Type;
@Input()
withRmBtn = false;
uploadUrl = (window as any).courseware.uploadUrl();
uploadData = (window as any).courseware.uploadData();
uploadUrl = (<any>window).courseware.uploadUrl();
uploadData = (<any>window).courseware.uploadData();
@Input()
needRemove = false;
......@@ -33,7 +32,7 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
@Input()
set audioUrl(url) {
this._audioUrl = url;
this._audioUrl = url
if (url) {
this.audio.src = this._audioUrl;
this.audio.load();
......@@ -145,7 +144,6 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
onBtnSwitchType() {
}
onBtnClearAudio() {
this.audioUrl = null;
this.audioRemoved.emit();
}
......@@ -188,7 +186,6 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
return true;
}
beforeUpload = (file: File) => {
this.audioUrl = null;
if (!this.checkSelectFile(file)) {
return false;
......@@ -199,7 +196,11 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
uploadSuccess = (url) => {
this.nzMessageService.info('Upload Success');
this.isUploading = false;
this.audioUrl = url;
if(typeof url == "string"){
this.audioUrl = url
}else{
this.audioUrl = url.url
}
}
uploadFailure = (err, file) => {
this.isUploading = false;
......
......@@ -116,14 +116,12 @@ export class MySprite extends Sprite {
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;
});
......@@ -269,14 +267,12 @@ export class Item extends MySprite {
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;
}
}
......@@ -341,9 +337,6 @@ export class ShapeRect extends MySprite {
setSize(w, h) {
this.width = w;
this.height = h;
console.log('w:', w);
console.log('h:', h);
}
drawShape() {
......@@ -375,44 +368,34 @@ export class HotZoneItem extends MySprite {
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.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.text) {
this.label.text = this.text;
}
this.label.visible = true;
}
hideLabel() {
if (!this.label) { return; }
this.label.visible = false;
}
......@@ -446,18 +429,14 @@ export class HotZoneItem extends MySprite {
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();
}
......@@ -465,14 +444,11 @@ export class HotZoneItem extends MySprite {
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();
......@@ -483,48 +459,201 @@ export class HotZoneItem 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]);
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 HotZoneImageItem extends MySprite {
lineDashFlag = false;
arrow: MySprite;
label: Label;
image: MySprite;
image_url: String;
labelBox: MySprite;
audio_url: String;
card_audio_url: String
scale
text;
arrowTop;
arrowRight;
init(image_url = null, callback?, handleSave?){
this.showImage(image_url, (img)=>{
callback && callback(img.width, img.height)
this.setSize(img.width*this.image.scaleX, img.height*this.image.scaleY)
handleSave && handleSave()
this.lineDashFlag = true;
this.showLineDash()
this.showLabel();
this.drawArrow()
})
}
setSize(w, h) {
this.width = w;
this.height = h;
}
showLabel(text = null) {
if (!this.label) {
this.labelBox = new MySprite(this.ctx);
this.labelBox.load('assets/default/bg_50_50.png').then(()=>{
this.labelBox.x = this.labelBox.width/2;
this.labelBox.y = this.labelBox.height/2;
});
this.label = new Label(this.ctx);
// this.label.anchorY = 0;
this.label.fontSize = '30px';
this.label.textAlign = 'center';
this.label.color = "#FFFFFF"
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;
}
hideLabel() {
if (!this.label) { return; }
this.label.visible = false;
}
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)
})
}
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;
}
refreshLabelScale() {
this.labelBox.scaleX = 75 / (this.labelBox.width*this.image.scaleX)
}
showLineDash() {
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);
}
}
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.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() {
super.draw();
if (this.lineDashFlag) {
this.drawFrame();
this.drawArrow();
......@@ -569,14 +698,12 @@ export class EditorItem extends MySprite {
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();
......@@ -672,8 +799,6 @@ export class Label extends MySprite {
drawText() {
// console.log('in drawText', this.text);
if (!this.text) { return; }
this.ctx.font = `${this.fontSize} ${this.fontName}`;
......@@ -688,7 +813,6 @@ export class Label extends MySprite {
this.ctx.fillStyle = '#000000';
this.ctx.fillText(this.text, 0, 0);
}
......@@ -713,23 +837,8 @@ export function getPosByAngle(angle, len) {
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); // 用反三角函数求弧度
......@@ -759,7 +868,5 @@ export function getAngleByPos(px, py, mx, my) {
angle = 360 - angle;
}
// console.log('angle: ', angle);
return angle;
}
<div class="p-image-children-editor">
<h5 style="margin-left: 2.5%;"> preview: </h5>
<div class="preview-box" #wrap>
<div style="float: left; width: 25%;border-right: 2px solid #ddd; border-bottom: 2px solid #ddd;">
<h5 style="margin-left: 2.5%;">预览:</h5>
<div id="canvas-container" style="margin:5px;">
<div class="preview-box" #wrap style="margin-bottom: 20px">
<canvas id="canvas" #canvas></canvas>
</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>
</div>
<div nz-row nzType="flex" nzAlign="middle">
<div nz-col nzSpan="5" nzOffset="1">
<h5> add background: </h5>
<h5 style="border-top: 2px solid #ddd;">背景图:</h5>
<div style="width: 200px;margin: auto;">
<div class="bg-box">
<app-upload-image-with-preview
[picUrl]="bgItem?.url"
(imageUploaded)="onBackgroundUploadSuccess($event)">
[picUrl]="bgItem.url"
(imageUploaded)="onBackgroundUploadSuccess($event)"
>
</app-upload-image-with-preview>
</div>
</div>
<div nz-col nzSpan="5" nzOffset="1" class="img-box"
*ngFor="let it of hotZoneArr; let i = index" >
<div style=" height: 40px;">
<h5> item-{{i+1}}
<i style="margin-left: 20px; margin-top: 2px; float: right; cursor:pointer" (click)="deleteItem($event, i)"
nz-icon [nzTheme]="'twotone'" [nzType]="'close-circle'" [nzTwotoneColor]="'#ff0000'"></i>
</h5>
</div>
<!--<div class="img-box-upload">-->
<!--<app-upload-image-with-preview-->
<!--[picUrl]="it.pic_url"-->
<!--(imageUploaded)="onImgUploadSuccessByImg($event, it)">-->
<!--</app-upload-image-with-preview>-->
<!--</div>-->
<!--<app-audio-recorder-->
<!--[audioUrl]="it.audio_url ? it.audio_url : null "-->
<!--(audioUploaded)="onAudioUploadSuccessByImg($event, it)"-->
<!--&gt;</app-audio-recorder>-->
<div style="float: left; width: 75%">
<div nzAlign="middle">
<div class="img-box clearfix" *ngFor="let it of hotZoneArr; let i = index" style="border-bottom: 1px solid #DDD; padding-bottom: 10px;" >
<div style="float: left; height: 115px; position: relative; width: 250px; ">
<h3> 第-{{ i + 1 }}-题 </h3>
<div style="position: absolute; bottom: 0;">
<h5> 题目音频 </h5>
<app-audio-recorder [audioUrl]="it.audio_url ? it.audio_url : null" (audioUploaded)="onAudioUploadSuccess($event, it, false)" ></app-audio-recorder>
</div>
</div>
<div style="float: left; height: 115px; position: relative; width: 250px; ">
<div style="position: absolute; bottom: 0;">
<h5> 卡片音频 </h5>
<app-audio-recorder [audioUrl]="it.card_audio_url ? it.card_audio_url : null" (audioUploaded)="onAudioUploadSuccess($event, it, true)" ></app-audio-recorder>
</div>
</div>
<div style="float: left;">
<div style="width:200px">
<app-upload-image-with-preview [picUrl]="it.image_url" (imageUploaded)="onImgUploadSuccessByImg($event, it)" ></app-upload-image-with-preview>
</div>
</div>
<div style="float: left; display: flex; flex-direction: column; padding-left: 10px;">
<button style="flex:1; margin-bottom: 5px;" nz-button nzType="dashed" (click)="handleMoveItemUp($event, i)" [disabled]="i==0">
<i nz-icon nzType="up" nzTheme="outline"></i>
上移
</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($event, i)">
<i nz-icon nzType="delete" nzTheme="outline"></i>
删除
</button>
</div>
</div>
<div nz-col nzSpan="5" nzOffset="1">
<div class="bg-box">
<button nz-button nzType="dashed" (click)="addBtnClick()"
class="add-btn">
<button
nz-button
nzType="dashed"
(click)="addBtnClick()"
class="add-btn"
>
<i nz-icon nzType="plus-circle" nzTheme="outline"></i>
<!--Add Image-->
Add hot zone
</button>
</div>
</div>
</div>
</div>
<nz-divider></nz-divider>
<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>
.p-image-children-editor {
width: 100%;
height: 100%;
border-radius: 0.5rem;
min-width: 1200px;
border: 2px solid #ddd;
.preview-box {
margin: auto;
width: 95%;
height: 35vw;
width: 100%;
// height: 35vw;
border: 2px dashed #ddd;
border-radius: 0.5rem;
background-color: #fafafa;
text-align: center;
color: #aaa;
.preview-img {
height: 100%;
width: auto;
}
}
.bg-box{
//width: 100%;
.bg-box {
margin-bottom: 1rem;
}
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.img-box {
margin-bottom: 1rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 1rem;
}
.img-box-upload{
width: 80%;
.img-box-upload {
width: 120px;
height: 80px;
}
.add-btn {
margin-top: 1rem;
width: 200px;
height: 90px;
display: flex;
align-items: center;
justify-content: center;
}
}
.save-box {
width: 100%;
......@@ -85,21 +72,6 @@ h5 {
margin-top: 1rem;
}
//@import '../../../style/common_mixin';
//
//.p-image-uploader {
......
import {Component, ElementRef, EventEmitter, HostListener, Input, OnChanges, OnDestroy, OnInit, Output, ViewChild} from '@angular/core';
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import {EditorItem, HotZoneItem, Label, MySprite} from './Unit';
import {EditorItem, HotZoneImageItem, Label, MySprite} from './Unit';
import TWEEN from '@tweenjs/tween.js';
......@@ -20,7 +20,6 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
@Input()
set bgItem(v) {
this._bgItem = v;
this.init();
}
get bgItem() {
......@@ -42,9 +41,14 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
@Output()
save = new EventEmitter();
@ViewChild('canvas', {static: true }) canvas: ElementRef;
@ViewChild('wrap', {static: true }) wrap: ElementRef;
// @HostListener('window:resize', ['$event'])
@ViewChild('canvas') canvas: ElementRef;
@ViewChild('wrap') wrap: ElementRef;
@HostListener('window:resize', ['$event'])
onResize(event) {
this.g_winResizeEventStream.next();
}
g_winResizeEventStream = new Subject();
canvasWidth = 1280;
canvasHeight = 720;
......@@ -64,7 +68,6 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
// 声音
bgAudio = new Audio();
images = new Map();
animationId: any;
......@@ -86,110 +89,112 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
changeSizeFlag = false;
changeTopSizeFlag = false;
changeRightSizeFlag = false;
hotZoneChanged = false;
scale = 1;
constructor() {
}
onResize(event) {
// this.winResizeEventStream.next();
constructor(private el:ElementRef) {
}
ngOnInit() {
this.initListener();
// this.init();
this.update();
}
ngOnDestroy() {
window.cancelAnimationFrame(this.animationId);
}
ngOnChanges() {
}
onBackgroundUploadSuccess(e) {
console.log('e: ', e);
this.bgItem.url = e.url;
this.refreshBackground();
this.refreshBackground(()=>{
this.autoSave()
});
}
refreshBackground(callBack = null) {
if (!this.bg) {
this.bg = new MySprite(this.ctx);
this.renderArr.push(this.bg);
}
const bg = this.bg;
if (this.bgItem.url) {
bg.load(this.bgItem.url).then(() => {
const rate1 = this.canvasWidth / bg.width;
const rate2 = this.canvasHeight / bg.height;
const rate = Math.min(rate1, rate2);
bg.setScaleXY(rate);
bg.x = this.canvasWidth / 2;
bg.y = this.canvasHeight / 2;
if (callBack) {
callBack();
}
});
}).catch((error)=>{
console.log(error)
})
}
}
addBtnClick() {
// this.imgArr.push({});
// this.hotZoneArr.push({});
const item = this.getHotZoneItem();
this.hotZoneArr.push(item);
this.refreshHotZoneId();
this.autoSave()
}
console.log('hotZoneArr:', this.hotZoneArr);
handleMoveItemUp(event,index){
if(index!=0){
this.hotZoneArr[index] = this.hotZoneArr.splice(index-1, 1, this.hotZoneArr[index])[0];
}else{
this.hotZoneArr.push(this.hotZoneArr.shift());
}
this.autoSave()
}
onImgUploadSuccessByImg(e, img) {
img.pic_url = e.url;
this.refreshImage (img);
handleMoveItemDown(event,index){
if(index!=this.hotZoneArr.length-1){
this.hotZoneArr[index] = this.hotZoneArr.splice(index+1, 1, this.hotZoneArr[index])[0];
}else{
this.hotZoneArr.unshift( this.hotZoneArr.splice(index,1)[0]);
}
this.autoSave()
}
refreshImage(img) {
onImgUploadSuccessByImg(e, item) {
item.init(e.url,(w, h)=>{
item.setScaleXY(Math.min(100 / w, 150 / h))
})
item.pic_url = e.url;
item.image_url = e.url;
this.refreshImage(item);
this.autoSave()
}
this.hideAllLineDash();
onAudioUploadSuccess(e, item, isCardAudio) {
if(isCardAudio){
item.card_audio_url = e.url;
}else{
item.audio_url = e.url;
}
this.autoSave()
}
refreshImage(img) {
this.hideAllLineDash();
img.picItem = this.getPicItem(img);
this.refreshImageId();
}
refreshHotZoneId() {
for (let i = 0; i < this.hotZoneArr.length; i++) {
this.hotZoneArr[i].index = i;
if (this.hotZoneArr[i]) {
this.hotZoneArr[i].text = 'item-' + (i + 1);
this.hotZoneArr[i].text = (i + 1);
}
}
}
......@@ -198,50 +203,44 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
refreshImageId() {
for (let i = 0; i < this.imgArr.length; i++) {
this.imgArr[i].id = i;
if (this.imgArr[i].picItem) {
this.imgArr[i].picItem.text = 'Image-' + (i + 1);
}
}
}
getHotZoneItem( saveData = null) {
getHotZoneItem( saveData = null, newRect?) {
const itemW = 200;
const itemH = 200;
const item = new HotZoneItem(this.ctx);
item.setSize(itemW, itemH);
item.anchorX = 0.5;
item.anchorY = 0.5;
item.x = this.canvasWidth / 2;
item.y = this.canvasHeight / 2;
if (saveData) {
const item = new HotZoneImageItem(this.ctx);
if(saveData){
item.init(saveData.media.image_url, (w, h)=>{
const saveRect = saveData.rect;
item.scaleX = saveRect.width / item.width;
item.scaleY = saveRect.height / item.height;
item.x = saveRect.x + saveRect.width / 2 ;
item.y = saveRect.y + saveRect.height / 2;
item.scaleX = (saveData.rect.width/saveData.scale) / w;
item.scaleY = (saveData.rect.height/saveData.scale) / h;
item.x = saveRect.x / saveData.scale + newRect.x
item.y = saveRect.y / saveData.scale + newRect.y
});
item.image_url = saveData.media.image_url
item.audio_url = saveData.media.audio_url
item.card_audio_url = saveData.media.card_audio_url
}else{
item.init("assets/default/bg_200_200.png" , ()=>{
item.image_url = "assets/default/bg_200_200.png"
item.x = this.canvasWidth / 2 - 100;
item.y = this.canvasHeight / 2 - 100;
},()=>this.autoSave());
}
item.showLineDash();
item.anchorX = 0.5;
item.anchorY = 0.5;
return item;
}
getPicItem(img, saveData = null) {
const item = new EditorItem(this.ctx);
item.load(img.pic_url).then( img => {
let maxW, maxH;
if (this.bg) {
maxW = this.bg.width * this.bg.scaleX;
......@@ -250,10 +249,8 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
maxW = this.canvasWidth;
maxH = this.canvasHeight;
}
let scaleX = maxW / 3 / item.width;
let scaleY = maxH / 3 / item.height;
if (item.height * scaleX < this.canvasHeight) {
item.setScaleXY(scaleX);
} else {
......@@ -261,46 +258,34 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
}
item.x = this.canvasWidth / 2;
item.y = this.canvasHeight / 2;
if (saveData) {
const saveRect = saveData.rect;
item.setScaleXY(saveRect.width / item.width);
item.x = saveRect.x + saveRect.width / 2 ;
item.y = saveRect.y + saveRect.height / 2;
} else {
item.showLineDash();
}
});
this.autoSave()
})
return item;
}
onAudioUploadSuccessByImg(e, img) {
img.audio_url = e.url;
this.autoSave()
}
deleteItem(e, i) {
// this.imgArr.splice(i , 1);
// this.refreshImageId();
this.hotZoneArr.splice(i, 1);
this.refreshHotZoneId();
this.autoSave()
}
init() {
this.initData();
this.initCtx();
this.initItem();
}
......@@ -309,81 +294,45 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
this.bgItem = {};
} else {
this.refreshBackground(() => {
// if (!this.imgItemArr) {
// this.imgItemArr = [];
// } else {
// this.initImgArr();
// }
// console.log('aaaaa');
if (!this.hotZoneItemArr) {
this.hotZoneItemArr = [];
} else {
this.initHotZoneArr();
}
});
}
}
initHotZoneArr() {
// console.log('this.hotZoneArr: ', this.hotZoneArr);
let curBgRect;
if (this.bg) {
curBgRect = this.bg.getBoundingBox();
} else {
curBgRect = {x: 0, y: 0, width: this.canvasWidth, height: this.canvasHeight};
}
let oldBgRect = this.bgItem.rect;
if (!oldBgRect) {
oldBgRect = curBgRect;
}
const rate = curBgRect.width / oldBgRect.width;
console.log('rate: ', rate);
this.hotZoneArr = [];
const arr = this.hotZoneItemArr.concat();
for (let i = 0; i < arr.length; i++) {
const data = JSON.parse(JSON.stringify(arr[i]));
// const img = {pic_url: data.pic_url};
data.rect.x *= rate;
data.rect.y *= rate;
data.rect.width *= rate;
data.rect.height *= rate;
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);
console.log('item: ', item);
// data.rect.x += curBgRect.x;
// data.rect.y += curBgRect.y;
const item = this.getHotZoneItem(data, {x:curBgRect.x,y:curBgRect.y});
// c//onsole.log("初始化存储数据", data)
this.hotZoneArr.push(item);
}
this.refreshHotZoneId();
// this.refreshImageId();
}
initImgArr() {
console.log('this.imgItemArr: ', this.imgItemArr);
let curBgRect;
if (this.bg) {
curBgRect = this.bg.getBoundingBox();
......@@ -397,9 +346,6 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
}
const rate = curBgRect.width / oldBgRect.width;
console.log('rate: ', rate);
this.imgArr = [];
const arr = this.imgItemArr.concat();
for (let i = 0; i < arr.length; i++) {
......@@ -424,13 +370,12 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
initData() {
this.canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight;
this.canvasHeight = (this.wrap.nativeElement.clientWidth/2)*3;
this.scale = 200/ this.wrap.nativeElement.clientWidth
this.mapScale = this.canvasWidth / this.canvasBaseW;
this.renderArr = [];
this.bg = null;
this.imgArr = [];
this.hotZoneArr = [];
}
......@@ -443,17 +388,12 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
mapDown(event) {
this.oldPos = {x: this.mx, y: this.my};
const arr = this.hotZoneArr;
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)) {
this.changeItemSize(item);
} else if (item.lineDashFlag && this.checkClickTarget(item.arrowTop)) {
......@@ -463,13 +403,12 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
} else {
this.changeCurItem(item);
}
this.hotZoneChanged = true;
return;
}
}
}
// this.hideAllLineDash();
}
mapMove(event) {
......@@ -483,11 +422,9 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
} else if (this.changeRightSizeFlag) {
this.changeRightSize();
} else {
const addX = this.mx - this.oldPos.x;
const addY = this.my - this.oldPos.y;
let addX = this.mx - this.oldPos.x;
let addY = this.my - this.oldPos.y;
this.curItem.x += addX;
this.curItem.y += addY;
}
......@@ -507,76 +444,48 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
changeSize() {
const rect = this.curItem.getBoundingBox();
let lenW = ( this.mx - (rect.x + rect.width / 2) ) * 2;
let lenH = ( (rect.y + rect.height / 2) - this.my ) * 2;
let distance = this.my - rect.y;
let lenW = this.mx - rect.x;
let lenH = rect.height - distance
let minLen = 20;
let s;
if (lenW < lenH) {
let sx,sy;
if (lenW < minLen) {
lenW = minLen;
}
s = lenW / this.curItem.width;
} else {
sx = lenW / this.curItem.width;
if (lenH < minLen) {
lenH = minLen;
}
s = lenH / this.curItem.height;
}
// console.log('s: ', s);
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() {
const rect = this.curItem.getBoundingBox();
// let lenW = ( this.mx - (rect.x + rect.width / 2) ) * 2;
let lenH = ( (rect.y + rect.height / 2) - this.my ) * 2;
let lenH = rect.y - this.my + rect.height;
this.curItem.y = this.my
let minLen = 20;
let s;
// if (lenW < lenH) {
// if (lenW < minLen) {
// lenW = minLen;
// }
// s = lenW / this.curItem.width;
//
// } else {
if (lenH < minLen) {
lenH = minLen;
}
s = lenH / this.curItem.height;
// }
// console.log('s: ', s);
this.curItem.scaleY = s;
this.curItem.refreshLabelScale();
this.curItem.setScaleXY(s);
}
changeRightSize() {
const rect = this.curItem.getBoundingBox();
let lenW = ( this.mx - (rect.x + rect.width / 2) ) * 2;
// let lenH = ( (rect.y + rect.height / 2) - this.my ) * 2;
let lenW = this.mx - rect.x;
let minLen = 20;
let s;
if (lenW < minLen) {
lenW = minLen;
}
s = lenW / this.curItem.width;
this.curItem.scaleX = s;
this.curItem.refreshLabelScale();
this.curItem.setScaleXY(s);
}
changeItemSize(item) {
......@@ -613,29 +522,13 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
update() {
if (!this.ctx) {
return;
}
this.animationId = window.requestAnimationFrame(this.update.bind(this));
// 清除画布内容
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
for (let i = 0; i < this.renderArr.length; i++) {
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);
TWEEN.update();
}
......@@ -647,24 +540,19 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
}
}
renderAfterResize() {
let offsetWidth = this.el.nativeElement.querySelector('#canvas-container').offsetWidth
this.el.nativeElement.querySelector('#canvas-container').style.height = '' + offsetWidth/2*3 + 'px'
this.canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight;
this.init();
}
initListener() {
// this.winResizeEventStream
// .pipe(debounceTime(500))
// .subscribe(data => {
// this.renderAfterResize();
// });
this.g_winResizeEventStream.pipe(debounceTime(500)).subscribe(data => {
this.renderAfterResize();
});
if (this.IsPC()) {
this.canvas.nativeElement.addEventListener('mousedown', (event) => {
setMxMyByMouse(event);
this.mapDown(event);
......@@ -712,18 +600,14 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
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 setParentOffset = () => {
const rect = this.canvas.nativeElement.getBoundingClientRect();
this.canvasLeft = rect.left;
this.canvasTop = rect.top;
......@@ -744,7 +628,6 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
checkClickTarget(target) {
const rect = target.getBoundingBox();
if (this.checkPointInRect(this.mx, this.my, rect)) {
return true;
......@@ -761,8 +644,8 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
return false;
}
saveClick() {
autoSave() {
console.log("Auto save")
const bgItem = this.bgItem;
if (this.bg) {
bgItem['rect'] = this.bg.getBoundingBox();
......@@ -770,44 +653,32 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
bgItem['rect'] = {x: 0, y: 0, width: Math.round(this.canvasWidth * 100) / 100, height: Math.round(this.canvasHeight * 100) / 100};
}
// const imgItemArr = [];
// const imgArr = this.imgArr;
// for (let i = 0; i < imgArr.length; i++) {
//
// const imgItem = {
// id: imgArr[i].id,
// pic_url: imgArr[i].pic_url,
// audio_url: imgArr[i].audio_url,
// };
// if (imgArr[i].picItem) {
// imgItem['rect'] = imgArr[i].picItem.getBoundingBox();
// imgItem['rect'].x -= bgItem['rect'].x;
// imgItem['rect'].y -= bgItem['rect'].y;
// }
// imgItemArr.push(imgItem);
// }
const hotZoneItemArr = [];
const hotZoneArr = this.hotZoneArr;
for (let i = 0; i < hotZoneArr.length; i++) {
const hotZoneItem = {
index: hotZoneArr[i].index,
};
hotZoneItem['rect'] = hotZoneArr[i].getBoundingBox();
hotZoneItem['rect'].x = Math.round( (hotZoneItem['rect'].x - bgItem['rect'].x) * 100) / 100;
hotZoneItem['rect'].y = Math.round( (hotZoneItem['rect'].y - bgItem['rect'].y) * 100) / 100;
hotZoneItem['rect'].width = Math.round( (hotZoneItem['rect'].width) * 100) / 100;
hotZoneItem['rect'].height = Math.round( (hotZoneItem['rect'].height) * 100) / 100;
const currentX = hotZoneItem['rect'].x
const currentY = hotZoneItem['rect'].y
hotZoneItem['media'] = {}
hotZoneItem['scale'] = this.scale
hotZoneItem['rect'].x = (Math.round( (currentX - bgItem['rect'].x) * 100) / 100) * this.scale;
hotZoneItem['rect'].y = (Math.round( (currentY - bgItem['rect'].y) * 100) / 100) * this.scale;
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['media'].image_url = hotZoneArr[i].image_url
hotZoneItem['media'].audio_url = hotZoneArr[i].audio_url?hotZoneArr[i].audio_url:""
hotZoneItem['media'].card_audio_url = hotZoneArr[i].card_audio_url?hotZoneArr[i].card_audio_url:""
hotZoneItemArr.push(hotZoneItem);
}
console.log('hotZoneItemArr: ', hotZoneItemArr);
this.save.emit({bgItem, hotZoneItemArr});
this.hotZoneChanged = false;
}
saveClick() {
console.log("Saved")
this.autoSave()
}
}
<div class="title-config">
<div class="title-wrap">
......@@ -8,10 +7,9 @@
<nz-select class="ml-1" style="width: 120px;" [(ngModel)]="__fontFamily"
(ngModelChange)="onChangeFontFamily($event)"
nzPlaceHolder="Font Family"
[nzDropdownMatchSelectWidth]="false">
<nz-option [nzValue]="font" nzCustomContent [nzLabel]="font" *ngFor="let font of fontFamilyList">
<span [ngStyle]="{'font-family': font}" >{{font}}</span>
</nz-option>
[nzDropdownMatchSelectWidth]="false"
>
<nz-option [nzValue]="font" [nzLabel]="font" *ngFor="let font of fontFamilyList"></nz-option>
</nz-select>
<nz-select class="ml-1" style="width: 110px;" [(ngModel)]="__fontSize"
(ngModelChange)="onChangeFontSize()"
......@@ -21,33 +19,28 @@
<div class="p-divider"></div>
<div class="i-tool-font-btn d-flex mr-2">
<div class="position-relative fa-icon" (click)="onChangeBold()">
<!-- <div class="fa fa-bold"></div>-->
<fa-icon icon="bold"></fa-icon>
<div class="fa fa-bold"></div>
</div>
</div>
<div class="i-tool-font-btn d-flex mr-2">
<div class="position-relative fa-icon" (click)="onChangeItalic()">
<!-- <div class="fa fa-italic"></div>-->
<fa-icon icon="italic"></fa-icon>
<div class="fa fa-italic"></div>
</div>
</div>
<div class="i-tool-font-btn d-flex mr-2">
<div class="position-relative fa-icon" (click)="onChangeUnderline()">
<!-- <div class="fa fa-underline"></div>-->
<fa-icon icon="underline"></fa-icon>
<div class="fa fa-underline"></div>
</div>
</div>
<div class="i-tool-font-btn d-flex">
<div class="position-relative fa-icon" (click)="onChangeStrikethrough()">
<!-- <div class="fa fa-strikethrough"></div>-->
<fa-icon icon="strikethrough"></fa-icon>
<div class="fa fa-strikethrough"></div>
</div>
</div>
<div class="p-divider"></div>
<div class="i-tool-font-color d-flex">
<div class="position-relative i-left flex-fill" (click)="onChangeFontColor($event)">
<!-- <div class="fa fa-font"></div>-->
<fa-icon icon="palette"></fa-icon>
<div class="fa fa-font"></div>
<div class="i-color" [style.background-color]="__fontColor"></div>
</div>
<div class="i-dropdown-menu" nzPlacement="bottom"
......@@ -58,14 +51,14 @@
</div>
<div class="p-divider"></div>
<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>
</div>
</div>
</div>
<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>
......@@ -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>
<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>
@import '../../style/common_mixin.css';
@import '../../style/common_mixin';
.title-config {
.letter-wrap{
......@@ -11,73 +11,39 @@
.type-row{
margin: 0;padding-top: 1rem;
}
}
@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") ;
.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: 'MMTextBook-Italic';
src: url("../../../assets/font/MMTextBook-Italic.otf") ;
}
@mixin tool-btn {
border: 1px solid #ddd;
display: flex;
......@@ -88,37 +54,16 @@
border-radius: 6px;
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{
width: 15px;
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 {
.p-title-box {
.p-title {
font-size: 20px;
}
.p-title-box input {
input {
width: 300px;
margin-left: 10px;
}
}
.p-content {
border: 1px solid #ddd;
......@@ -140,31 +85,33 @@
align-items: center;
border-bottom: 1px solid #ddd;
}
// save
.i-tool-save {
//@include tool-btn();
// save
.i-tool-save {
@include tool-btn();
color: white;
}
.i-tool-save:disabled {
}
.i-tool-save:disabled {
color: #555;
}
}
// font-size
.i-tool-font-size {
//@include tool-btn();
// font-size
.i-tool-font-size {
@include tool-btn();
width: 37px;
}
.i-tool-font-size:hover {
& > span {
position: absolute;
top: -5px;
right: 5px;
}
}
.i-tool-font-size:hover {
color: black;
border-color: #bbb;
}
}
// font-color
.i-tool-font-color, .i-tool-font-btn {
// font-color
.i-tool-font-color, .i-tool-font-btn {
border: 1px solid #ddd;
//padding: 3px 7px;
border-radius: 6px;
......@@ -208,20 +155,20 @@
transform: scale(0.6);
}
}
}
.i-tool-font-btn{
}
.i-tool-font-btn{
width: 31px;
}
.fa-icon{
}
.fa-icon{
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
// bg-color
.i-tool-bg-color {
}
// bg-color
.i-tool-bg-color {
@include tool-btn();
padding: 0 9px;
::ng-deep > span {
......@@ -236,14 +183,17 @@
background-color: white;
margin-left: 10px;
}
}
}
// horizontal-center
.i-tool-horizontal-center {
// horizontal-center
.i-tool-horizontal-center {
@include tool-btn();
width: 37px;
}
}
.p-box {
width: 1280px;
height: 720px;
......@@ -253,7 +203,9 @@
overflow: hidden;
}
.p-sentence {
@include k-no-select();
}
.p-animation-index-box {
.i-animation-index {
......@@ -326,6 +278,7 @@
::ng-deep .ant-radio-button-wrapper {
padding: 0 10px;
@include k-no-select();
}
.i-toolbox {
......@@ -356,6 +309,7 @@
cursor: pointer;
text-align: left;
display: flex;
@include k-no-select();
}
.i-active {
background-color: antiquewhite;
......
import {
Component,
ElementRef,
......@@ -11,82 +10,6 @@ import {
ViewChild
} 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({
selector: 'app-lesson-title-config',
templateUrl: './lesson-title-config.component.html',
......@@ -96,45 +19,22 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
fontFamilyList = [
'Arial',
'BRLNSB',
'BRLNSDB',
'BRLNSR',
'GOTHIC',
'GOTHICB',
// "GOTHICBI",
// "GOTHICI",
'MMTextBook',
// "MMTextBook-Bold",
// "MMTextBook-Italic",
// "MMTextBook-BoldItalic",
'ARBLI'
];
colorList = [
'#000000',
'#111111',
'#ffffff',
'#595959',
'#0075c2',
'#c61c1e',
'#9cbc3a',
'#008000',
'#FF0000',
'#D2691E',
'#9cbc3a'
];
MIN_FONT_SIZE = 1;
MAX_FONT_SIZE = 7;
isShowFontColorPane = false;
isShowBGColorPane = false;
fontSizeRange = [
// {name: '1号', value: 9},
// {name: '2号', value: 13},
// {name: '3号', value: 16},
// {name: '4号', value: 18},
// {name: '5号', value: 24},
// {name: '6号', value: 32},
];
fontSizeRange: number[];
editorContent = '';
......@@ -145,17 +45,25 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
loopCnt = 0;
maxLoops = 20;
@ViewChild('titleEl', {static: true}) titleEl: ElementRef;
groupIconsCount = {
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;
@Input()
titleObj = {
type: 'a',
content: '',
icons: [],
audio_url: ''
};
@Input()
withIcon = true;
@Output()
titleUpdated = new EventEmitter();
......@@ -176,12 +84,16 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
let defObj = this.titleObj;
if (!vars.titleObj.currentValue) {
defObj = {
type: 'a',
content: '',
icons: [],
audio_url: ''
};
} else {
defObj = vars.titleObj.currentValue;
}
this.titleObj.icons = defObj.icons || [];
this.titleObj.type = defObj.type || 'a';
this.titleObj.content = defObj.content || '';
this.titleObj.audio_url = defObj.audio_url || '';
this.titleEW.document.body.innerHTML = this.titleObj.content;
......@@ -190,23 +102,33 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
ngOnInit() {
if (!this.titleObj) {
this.titleObj = {
type: 'a',
content: '',
icons: [],
audio_url: ''
};
}
this.titleObj.icons = this.titleObj.icons || [];
this.titleObj.type = this.titleObj.type || 'a';
this.titleObj.content = this.titleObj.content || '';
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;
console.log('this.titleEW', this.titleEW);
const tdoc = this.titleEW.document;
tdoc.designMode = 'on';
tdoc.designMode = "on";
tdoc.open('text/html', 'replace');
tdoc.write(this.editorContent);
tdoc.close();
tdoc.addEventListener('keypress', this.keyPress, true);
tdoc.addEventListener('blur', () => {
tdoc.addEventListener("keypress", this.keyPress, true);
tdoc.addEventListener("blur", () => {
if (this.titleObj.content === this.titleEW.document.body.innerHTML.trim()) {
return;
}
......@@ -237,7 +159,30 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
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) {
try {
......@@ -250,9 +195,9 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
const key = String.fromCharCode(evt.charCode).toLowerCase();
let cmd = '';
switch (key) {
case 'b': cmd = 'bold'; break;
case 'i': cmd = 'italic'; break;
case 'u': cmd = 'underline'; break;
case 'b': cmd = "bold"; break;
case 'i': cmd = "italic"; break;
case 'u': cmd = "underline"; break;
}
......@@ -269,13 +214,10 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
alert(e);
}
}
execEditorCommand(command, option?: any) {
console.log('sssss');
try {
this.titleEW.focus();
const result = this.titleEW.document.execCommand(command, false, option);
console.log(result);
this.titleEW.document.execCommand(command, false, option);
this.loopCnt = 0;
return false;
......@@ -287,7 +229,7 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
}, 100);
this.loopCnt += 1;
} else {
alert('Error executing command.');
alert("Error executing command.");
}
}
}
......@@ -300,7 +242,7 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
this.execEditorCommand('forecolor', this.__fontColor);
}
onChangeFontFamily(font) {
this.execEditorCommand('fontName', font);
this.execEditorCommand('fontname', font);
}
onChangeFontSize(size?: any) {
......@@ -330,10 +272,9 @@ export class LessonTitleConfigComponent implements OnInit, OnChanges, OnDestroy,
this.titleUpdated.emit(this.titleObj);
}
shouldSave = () => {
console.log('title shouldSave', this.titleObj);
console.log('title shouldSave');
this.titleObj.content = this.titleEW.document.body.innerHTML.trim();
this.titleUpdated.emit(this.titleObj);
}
}
@import '../../style/common_mixin.css';
@import '../../style/common_mixin';
.cmp-player-content-wrapper{
max-height: 100%;
......
......@@ -18,7 +18,7 @@ import {
export class PlayerContentWrapperComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
@ViewChild('wrapperEl', {static: true }) wrapperEl: ElementRef;
@ViewChild('wrapperEl') wrapperEl: ElementRef;
// // aspect ratio?
@Input() ratio;
......
......@@ -5,21 +5,16 @@
[nzAction]="uploadUrl"
[nzData]="uploadData"
(nzChange)="handleChange($event)">
<!--[nzBeforeUpload]="customUpload">-->
<div class="p-box d-flex align-items-center">
<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>
<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 class="p-upload-progress-bg" *ngIf="uploading">
<div class="i-bg" [style.width]="progress+'%'"></div>
<div class="i-text">
<fa-icon icon="cloud-upload-alt"></fa-icon>
<fa name="cloud-upload"></fa>
Uploading...
</div>
</div>
......@@ -32,6 +27,6 @@
nz-popconfirm nzTitle="Are you sure ?"
(nzOnConfirm)="onDelete()"
>
<i nz-icon nzType="close" nzTheme="outline"></i>
<i nz-icon type="close" theme="outline"></i>
</div>
</div>
@import '../../style/common_mixin.css';
@import '../../style/common_mixin';
.p-image-uploader {
position: relative;
......@@ -52,15 +52,10 @@
.p-preview {
width: 100%;
height: 100%;
background-size: contain;
background-repeat: no-repeat;
background-position: 50% 50%;
//background-image: url("https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png");
@include k-img-bg();
}
}
.d-flex{
display: flex;
}
}
.p-btn-delete {
......
......@@ -45,9 +45,6 @@ export class UploadImageWithPreviewComponent implements OnDestroy, OnChanges {
handleChange(info: { type: string, file: UploadFile, event: any }): void {
console.log('info:' , info);
switch (info.type) {
case 'start':
// this.isUploading = true;
......
<div class="p-video-box">
<div class="up-video" style="display: flex;">
<!--<nz-upload class="" [nzDisabled]="!showUploadBtn"-->
<!--[nzShowUploadList]="false"-->
......@@ -16,7 +16,8 @@
<button type="button" nz-button nzType="default" *ngIf="showUploadBtn" [disabled]="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>Select Video</span>-->
</button>
......@@ -55,9 +56,9 @@
</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">
<i nz-icon nzType="upload" nzTheme="outline"></i>
<i nz-icon type="upload" theme="outline"></i>
<div class="m-3"></div>
<span>Click here to upload video</span>
<div class="mt-5 p-progress-bar" *ngIf="uploading">
......@@ -69,26 +70,26 @@
[ngClass]="{'smart-bar': showUploadBtn}" >
<div class="i-bg" [style.width]="progress+'%'"></div>
<div class="i-text">
<fa-icon icon="cloud-upload-alt"></fa-icon>
<fa name="cloud-upload"></fa>
Uploading...
</div>
</div>
<div class="p-upload-check-bg" *ngIf="checking">
<div class="i-bg" [style.width]="progress+'%'"></div>
<div class="i-text">
<fa-icon icon="cloud-upload-alt"></fa-icon>
<i nz-icon nzType="loading" nzTheme="outline"></i>Checking...
<fa name="cloud-upload"></fa>
<i nz-icon type="loading" theme="outline"></i>Checking...
</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 [src]="safeVideoUrl(videoUrl)" controls #videoNode></video>
<video [src]="safeVideoUrl(videoUrl)" controls #videoNode (loadedmetadata)="videoLoadedMetaData()"></video>
</div>
</div>
<div [style.display]="!checkVideoExists?'none':''">
<span><i nz-icon nzType="loading" nzTheme="outline"></i> checking file to upload</span>
</div>
<span><i nz-icon type="loading" theme="outline"></i> checking file to upload</span>
</div>
@import '../../style/common_mixin.css';
/*.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%);
}
}*/
@import '../../style/common_mixin';
.p-video-uploader {
position: relative;
display: block;
......@@ -33,33 +17,25 @@
background-color: #fafafa;
text-align: center;
color: #aaa;
}
}
.p-upload-icon {
.p-upload-icon {
text-align: center;
margin: auto;
}
.p-upload-icon .anticon-upload {
.anticon-upload {
color: #888;
font-size: 5rem;
}
p-progress-bar {
}
.p-progress-bar {
position: relative;
width: 20rem;
height: 1.5rem;
border: 1px solid #ccc;
border-radius: 1rem;
}
.p-progress-bar .p-progress-bg {
.p-progress-bg {
background-color: #1890ff;
border-radius: 1rem;
height: 100%;
}
.p-progress-bar .p-progress-value {
}
.p-progress-value {
position: absolute;
top: 0;
left: 0;
......@@ -70,19 +46,21 @@ p-progress-bar {
text-align: center;
font-size: 0.9rem;
line-height: 1.5rem;
}
.p-preview {
}
}
}
.p-preview {
width: 100%;
height: 100%;
//background-image: url("https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png");
}
.p-preview video{
video{
max-height: 100%;
max-width: 100%;
position: absolute;
display: flex;
}
}
}
}
.p-btn-delete {
position: absolute;
right: -0.5rem;
......
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';
......@@ -24,7 +24,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
@Input()
videoUrl = '';
@ViewChild('videoNode', {static: true })
@ViewChild('videoNode')
videoNode: ElementRef;
......@@ -47,8 +47,8 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
item: any;
// videoItem = null;
uploadUrl = (window as any).courseware.uploadUrl();
uploadData = (window as any).courseware.uploadData();
uploadUrl = (<any> window).courseware.uploadUrl();
uploadData = (<any> window).courseware.uploadData();
constructor(private nzMessageService: NzMessageService,
private sanitization: DomSanitizer
......@@ -71,7 +71,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
}
safeVideoUrl(url) {
console.log(url);
console.log(url)
return this.sanitization.bypassSecurityTrustResourceUrl(url); // `${url}`;
}
videoLoadedMetaData() {
......@@ -79,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);
......@@ -109,7 +109,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
break;
case 'progress':
this.progress = info.event.percent;
this.progress = parseInt(info.event.percent, 10);
this.doProgress(this.progress);
break;
}
......@@ -152,9 +152,9 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
if (duration) {
duration = duration * 1000;
}
file.height = height;
file.width = width;
file.duration = duration;
file['height'] = height;
file['width'] = width;
file['duration'] = duration;
vid.preload = 'none';
vid.src = '';
vid.remove();
......
@import '../style/common_mixin.css';
.model-content {
width: 100%;
height: 100%;
}
<div class="model-content">
<div style="position: absolute; left: 200px; top: 100px; width: 800px;">
<input type="text" nz-input [(ngModel)]="item.text" (blur)="save()">
<app-upload-image-with-preview
[picUrl]="item.pic_url"
(imageUploaded)="onImageUploadSuccess($event, 'pic_url')"
></app-upload-image-with-preview>
<app-audio-recorder
[audioUrl]="item.audio_url"
(audioUploaded)="onAudioUploadSuccess($event, 'audio_url')"
></app-audio-recorder>
<app-custom-hot-zone></app-custom-hot-zone>
<app-upload-video></app-upload-video>
<app-lesson-title-config></app-lesson-title-config>
<div class="card-config">
<div class="card-item" style="padding: 0.5vw;" >
<div class="card-item-content border" style=" width: 1000px;">
<div class="title" >
人物设置
</div>
<div class="section" >
<div class="section-content">
<div style="display: flex; margin-bottom: 10px;">
<div style="flex:1">
性别:
</div>
<div style="flex:9">
<nz-radio-group [(ngModel)]="item.contentObj.sex" (ngModelChange)="saveItem()" >
<label nz-radio [nzValue]="'male'">男孩</label>
<label nz-radio [nzValue]="'female'">女孩</label>
</nz-radio-group>
</div>
</div>
</div>
</div>
<div class="title" >
音频设置
</div>
<div class="section">
<div *ngFor="let it of item.contentObj.audio; let i = index" style="display: flex; margin-bottom: 10px;">
<div style="flex:1;">
{{this.roleMapping[i]}}:
</div>
<div style="flex:9">
<app-audio-recorder [audioUrl]="it.url" (audioUploaded)="onAudioUploadSuccessByItem($event, it)" ></app-audio-recorder>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
\ No newline at end of file
@import "../style/common_mixin";
.model-content {
margin: 10px;
.card-config {
width: 100%;
height: 100%;
box-sizing: border-box;
.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: column;
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;
}
}
}
}
}
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';
const defaultData = [
{audio_url:"", displayType:"image", text:"This is demoA.", image_url:""},
{audio_url:"", displayType:"text", text:"This is demoB.", image_url:""},
{audio_url:"", displayType:"image", text:"This is demoC.", image_url:""},
{audio_url:"", displayType:"text", text:"This is demoD.", image_url:""}
]
const defauleFormData = {
sex:"male",
audio: [
{url: ""},
{url: ""},
{url: ""},
{url: ""},
{url: ""},
{url: ""},
]
}
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
// 储存数据用
saveKey = "test_0011";
// 储存对象
item;
constructor(private appRef: ApplicationRef,private changeDetectorRef: ChangeDetectorRef) {
export class FormComponent implements OnInit, OnChanges, OnDestroy {
_item: any;
dataArray: Array<Object> = [];
hotZoneItemArr: Array<Object> = [];
bgItem: Object;
KEY = 'DataKey_East_L215';
roleMapping = [
"建筑工",
"消防员",
"警察",
"教师",
"农民伯伯",
"医生"
]
set item(item) {
this._item = item;
}
get item() {
return this._item;
}
@Output()
update = new EventEmitter();
constructor(private appRef: ApplicationRef) {
}
ngOnInit() {
this.item = {};
// 获取存储的数据
(<any> window).courseware.getData((data) => {
this.item.contentObj = {};
const getData = (<any> window).courseware.getData;
getData((data) => {
// console.log("读取数据", data)
if (data) {
this.item = data;
} else {
this.item = {};
}
console.log(this.item)
if ( !this.item.contentObj ) {
this.item.contentObj = defauleFormData;
}
if(!this.item.contentObj.sex){
this.item.contentObj = defauleFormData;
}
if(!this.item.contentObj.audio || this.item.contentObj.audio.length === 0){
this.item.contentObj = defauleFormData;
}
this.init();
this.changeDetectorRef.markForCheck();
this.changeDetectorRef.detectChanges();
this.refresh();
this.save()
}, this.KEY);
}
ngOnChanges() {
}, this.saveKey);
}
ngOnDestroy() {
}
init() {
// if (this.item.contentObj.dataArray) {
// this.dataArray = this.item.contentObj.dataArray;
// } else {
// this.dataArray = this.getDefaultPicArr();
// this.item.contentObj.dataArray = this.dataArray;
// }
}
ngOnChanges() {
cardItemData(){
return {audio_url:"", displayType:"text", text:"", image_url:""}
}
ngOnDestroy() {
cardChoiceData(){
return { isText: true, text: "", image_url: "" }
}
getDefaultPicArr() {
let arr = defaultData;
return arr;
}
initData() {
}
init() {
handleMoveItemUp(index){
if(index!=0){
this.item.contentObj.dataArray[index] = this.item.contentObj.dataArray.splice(index-1, 1, this.item.contentObj.dataArray[index])[0];
}else{
this.item.contentObj.dataArray.push(this.item.contentObj.dataArray.shift());
}
this.save()
}
handleMoveItemDown(index){
if(index!=this.item.contentObj.dataArray.length-1){
this.item.contentObj.dataArray[index] = this.item.contentObj.dataArray.splice(index+1, 1, this.item.contentObj.dataArray[index])[0];
}else{
this.item.contentObj.dataArray.unshift( this.item.contentObj.dataArray.splice(index,1)[0]);
}
this.save()
}
/**
* 储存图片数据
* @param e
*/
onImageUploadSuccess(e, key) {
deleteItem(index){
this.item.contentObj.dataArray.splice(index,1)
this.save()
}
addChoice(questionIndex) {
// let item = this.cardChoiceData();
// this.dataArray[questionIndex].choice.incorrect.push(item);
// this.saveItem();
}
this.item[key] = e.url;
onImageUploadSuccessByItem(e, item) {
item.image_url = e.url
this.save();
}
/**
* 储存音频数据
* @param e
*/
onAudioUploadSuccess(e, key) {
onAudioUploadSuccessByItem(e, it) {
it.url = e.url;
this.save();
}
this.item[key] = e.url;
onTitleAudioUploadSuccess(e) {
this.item.contentObj.titleAudio_url = e.url;
this.save();
}
addItem() {
let item = this.cardItemData();
this.dataArray.push(item);
this.saveItem();
}
radioClick(it, radioValue) {
it.radioValue = radioValue;
this.saveItem();
}
clickCheckBox() {
this.saveItem();
}
saveItem() {
this.save();
}
/**
* 储存数据
*/
save() {
(<any> window).courseware.setData(this.item, null, this.saveKey);
(<any> window).courseware.setData(this.item, null, this.KEY);
this.refresh();
console.log("保存", this.item)
}
/**
* 刷新 渲染页面
*/
refresh() {
setTimeout(() => {
this.appRef.tick();
}, 1);
}
}
import {
MySprite,
getMinScale,
ShapeRect,
tweenChange,
randomSortByArr,
Label,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem,
ShapeRectNew,
waterWave,
ShapeCircle
} from "./Unit";
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 = []
playAudio = function( key, now = false, callback = null) {
const audio = this.audio.get(key);
if (audio) {
if (now) {
audio.pause();
audio.currentTime = 0;
}
if (callback) {
audio.onended = () => {
let index = this._playingNow.indexOf(audio)
if(index != -1){
this._playingNow.splice(index,1)
}
callback();
};
}
audio.play();
audio.callback = callback
this._playingNow.push(audio)
this._currentPlayAudio = audio;
}
}
stopAllAudio(){
this._playingNow.forEach(audio=>{
try{
audio.onended && audio.onended()
audio.pause();
audio.currentTime = 0;
}catch(err){
console.log(err)
}
})
this._playingNow = []
}
stopAudio(){
if(this._currentPlayAudio){
this._currentPlayAudio.pause();
this._currentPlayAudio.currentTime = 0;
}
}
// 异步加载图片 音频资源
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] = {}
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;
}
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
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)
element.ref.initScaleX = scale.sx
element.ref.initScaleY = scale.sy
element.initX = position.x
element.initY = position.y
element.ref.scaleX = scale.sx
element.ref.scaleY = scale.sy
element.ref.x = element.initX
element.ref.y = element.initY
}
element.rePosition()
return this.cartoonElementsBuffer[id]
}
createLabel = ({
text,
fontName,
fontColor,
fontSize,
textAlign
}, initX?, initY?)=>{
let element = new Label()
element.text = text;
element.fontName = fontName;
element.fontColor = fontColor;
element.fontSize = fontSize;
element.textAlign = textAlign;
element.x = initX;
element.y = initY;
return element
}
getCartoonElementRef = (key)=>{
if(this.cartoonElementsBuffer[key]){
return this.cartoonElementsBuffer[key].ref;
}else{
return undefined
}
}
getCartoonElement = (key)=>{
return this.cartoonElementsBuffer[key]
}
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
}
}
}
\ No newline at end of file
import TWEEN from '@tweenjs/tween.js';
interface AirWindow extends Window {
air: any;
curCtx: any;
}
declare let window: AirWindow;
import TWEEN from "@tweenjs/tween.js";
import simplexNoise from "../../assets/libs/simplex-noise/simplex-noise.min.js"
import { del } from "selenium-webdriver/http";
import construct = Reflect.construct;
class Sprite {
x = 0;
y = 0;
color = '';
color = "";
radius = 0;
alive = false;
margin = 0;
angle = 0;
ctx;
id;
constructor(ctx = null) {
if (!ctx) {
this.ctx = window.curCtx;
this.ctx = window["curCtx"];
} else {
this.ctx = ctx;
}
......@@ -27,18 +23,10 @@ class Sprite {
update($event) {
this.draw();
}
draw() {
}
draw() {}
}
export class MySprite extends Sprite {
_width = 0;
_height = 0;
_anchorX = 0;
......@@ -53,14 +41,6 @@ export class MySprite extends Sprite {
skewX = 0;
skewY = 0;
_shadowFlag = false;
_shadowColor;
_shadowOffsetX = 0;
_shadowOffsetY = 0;
_shadowBlur = 5;
_radius = 0;
children = [this];
childDepandVisible = true;
......@@ -69,50 +49,26 @@ export class MySprite extends Sprite {
img;
_z = 0;
init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) {
if (imgObj) {
this.img = imgObj;
this.width = this.img.width;
this.height = this.img.height;
}
this.anchorX = anchorX;
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) {
if (!this.visible && this.childDepandVisible) {
return;
}
this.draw();
}
draw() {
this.ctx.save();
this.drawInit();
......@@ -120,95 +76,49 @@ export class MySprite extends Sprite {
this.updateChildren();
this.ctx.restore();
}
drawInit() {
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.globalAlpha = this.alpha;
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() {
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) {
this.ctx.drawImage(this.img, this._offX, this._offY);
}
}
updateChildren() {
if (this.children.length <= 0) {
return;
}
if (this.children.length <= 0) { return; }
for (const child of this.children) {
if (child === this) {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i] === this) {
if (this.visible) {
this.drawSelf();
}
} else {
child.update();
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;
});
......@@ -225,11 +135,9 @@ export class MySprite extends Sprite {
return a._z - b._z;
});
if (this.childDepandAlpha) {
child.alpha = this.alpha;
}
}
removeChild(child) {
const index = this.children.indexOf(child);
......@@ -241,18 +149,18 @@ export class MySprite extends Sprite {
removeChildren() {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i]) {
if (this.children[i] !== this) {
if (this.children[i] != this) {
this.children.splice(i, 1);
i --;
i--;
}
}
}
}
_changeChildAlpha(alpha) {
for (const child of this.children) {
if (child !== this) {
child.alpha = alpha;
for (let i = 0; i < this.children.length; i++) {
if (this.children[i] != this) {
this.children[i].alpha = alpha;
}
}
}
......@@ -304,10 +212,7 @@ export class MySprite extends Sprite {
}
getBoundingBox() {
const getParentData = (item) => {
const getParentData = item => {
let px = item.x;
let py = item.y;
......@@ -315,7 +220,6 @@ export class MySprite extends Sprite {
let sy = item.scaleY;
const parent = item.parent;
if (parent) {
const obj = getParentData(parent);
const _x = obj.px;
......@@ -328,16 +232,13 @@ export class MySprite extends Sprite {
sx *= _sx;
sy *= _sy;
}
return {px, py, sx, 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);
......@@ -348,40 +249,85 @@ export class MySprite extends Sprite {
// const width = this.width * Math.abs(this.scaleX);
// const height = this.height * Math.abs(this.scaleY);
return {x, y, width, height};
return { x, y, width, height };
}
}
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
}
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
}
if(y<c_y2){
y = c_y2
}
this.ctx[i === 0 ? "moveTo" : "lineTo"](x, y);
}
this.ctx.arc(a,b,r,0,Math.PI);
this.ctx.closePath();
this.ctx.fillStyle = color;
this.ctx.fill();
}
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 {
r = 0;
g = 0;
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 );
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];
......@@ -390,8 +336,6 @@ export class ColorSpr extends MySprite {
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;
}
......@@ -400,34 +344,26 @@ export class ColorSpr extends MySprite {
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
}
drawSelf() {
super.drawSelf();
this.createGSCanvas();
}
}
export class GrayscaleSpr extends MySprite {
grayScale = 120;
createGSCanvas() {
if (!this.img) {
return;
}
const rect = this.getBoundingBox();
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 );
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];
......@@ -441,37 +377,26 @@ export class GrayscaleSpr extends MySprite {
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
}
drawSelf() {
super.drawSelf();
this.createGSCanvas();
}
}
export class BitMapLabel extends MySprite {
labelArr;
baseUrl;
setText(data, text) {
this.labelArr = [];
const labelArr = [];
const tmpArr = text.split('');
const tmpArr = text.split("");
let totalW = 0;
let h = 0;
for (const tmp of tmpArr) {
for (let i = 0; i < tmpArr.length; i++) {
const label = new MySprite(this.ctx);
label.init(data[tmp], 0);
label.init(data[tmpArr[i]], 0);
this.addChild(label);
labelArr.push(label);
......@@ -479,60 +404,52 @@ export class BitMapLabel extends MySprite {
h = label.height;
}
this.width = totalW;
this.height = h;
let offX = -totalW / 2;
for (const label of labelArr) {
label.x = offX;
offX += label.width;
for (let i = 0; i < labelArr.length; i++) {
labelArr[i].x = offX;
offX += labelArr[i].width;
}
this.labelArr = labelArr;
}
}
export class Label extends MySprite {
text: string;
text: String;
// fontSize:String = '40px';
fontName = 'Verdana';
textAlign = 'left';
fontName: String = "Verdana";
textAlign: String = "left";
fontSize = 40;
fontColor = '#000000';
fontColor = "#000000";
fontWeight = 900;
_maxWidth;
maxWidth;
outline = 0;
outlineColor = '#ffffff';
// _shadowFlag = false;
// _shadowColor;
// _shadowOffsetX;
// _shadowOffsetY;
// _shadowBlur;
outlineColor = "#ffffff";
maxSingalLineWidth = 0;
_shadowFlag = false;
_shadowColor;
_shadowOffsetX;
_shadowOffsetY;
_shadowBlur;
_outlineFlag = false;
_outLineWidth;
_outLineColor;
_warpLineY = 0;
constructor(ctx = null) {
super(ctx);
this.init();
}
refreshSize() {
this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight;
this._width = this.ctx.measureText(this.text).width;
......@@ -540,12 +457,10 @@ export class Label extends MySprite {
this.refreshAnchorOff();
this.ctx.restore();
}
setMaxSize(w) {
this._maxWidth = w;
this.maxWidth = w;
this.refreshSize();
if (this.width >= w) {
this.scaleX *= w / this.width;
......@@ -554,7 +469,6 @@ export class Label extends MySprite {
}
show(callBack = null) {
this.visible = true;
if (this.alpha >= 1) {
......@@ -564,7 +478,7 @@ export class Label extends MySprite {
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(() => {
.onComplete(function() {
if (callBack) {
callBack();
}
......@@ -572,47 +486,41 @@ export class Label extends MySprite {
.start(); // Start the tween immediately.
}
// setShadow(offX = 0, offY = 2, blur = 2, color = 'rgba(0, 0, 0, 0.2)') {
//
// this._shadowFlag = true;
// this._shadowColor = color;
// // 将阴影向右移动15px,向上移动10px
// this._shadowOffsetX = 5;
// this._shadowOffsetY = 5;
// // 轻微模糊阴影
// this._shadowBlur = 5;
// }
setOutline(width = 5, color = '#ffffff') {
setShadow(offX = 2, offY = 2, blur = 2, color = "rgba(0, 0, 0, 0.2)") {
this._shadowFlag = true;
this._shadowColor = color;
// 将阴影向右移动15px,向上移动10px
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
// 轻微模糊阴影
this._shadowBlur = blur;
}
setOutline(width = 5, color = "#ffffff") {
this._outlineFlag = true;
this._outLineWidth = width;
this._outLineColor = color;
}
drawText() {
// console.log('in drawText', this.text);
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.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;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight;
if (this._outlineFlag) {
......@@ -623,61 +531,152 @@ export class Label extends MySprite {
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);
}
// 当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._warpLineY /2
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);
// 右边线
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.drawText();
this.drawShape();
}
}
export class RichTextOld extends Label {
textArr = [];
fontSize = 40;
setText(text: string, words) {
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');
newText = newText.replace( re, `#${word}#`);
const re = new RegExp(word, "g");
newText = newText.replace(re, `#${word}#`);
// newText = newText.replace(word, `#${word}#`);
}
this.textArr = newText.split('#');
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.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight;
let curX = 0;
for (const text of this.textArr) {
const w = this.ctx.measureText(text).width;
for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width;
curX += w;
}
......@@ -686,12 +685,9 @@ export class RichTextOld extends Label {
this.refreshAnchorOff();
this.ctx.restore();
}
show(callBack = null) {
// console.log(' in show ');
this.visible = true;
// this.alpha = 0;
......@@ -699,185 +695,119 @@ export class RichTextOld extends Label {
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(() => {
.onComplete(function() {
if (callBack) {
callBack();
}
})
.start(); // Start the tween immediately.
}
drawText() {
// console.log('in drawText', this.text);
if (!this.text) { return; }
if (!this.text) {
return;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.textBaseline = "middle";
this.ctx.fontWeight = 900;
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = '#ffffff';
this.ctx.strokeStyle = "#ffffff";
// this.ctx.strokeText(this.text, 0, 0);
this.ctx.fillStyle = '#000000';
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';
if ((i + 1) % 2 == 0) {
this.ctx.fillStyle = "#c8171e";
} else {
this.ctx.fillStyle = '#000000';
this.ctx.fillStyle = "#000000";
}
this.ctx.fillText(this.textArr[i], curX, 0);
curX += w;
}
}
}
export class RichText extends Label {
disH = 30;
constructor(ctx?: any) {
constructor(ctx) {
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.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 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;
for (let a = 0; a < chr.length; a++) {
if (
this.ctx.measureText(temp).width < w &&
this.ctx.measureText(temp + chr[a]).width <= w
) {
temp += " " + chr[a];
} else {
row.push(temp);
temp = ' ' + c;
temp = " " + chr[a];
}
}
row.push(temp);
const x = 0;
const y = -row.length * disH / 2;
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
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
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';
fillColor = "#FF0000";
setSize(w, h) {
this.width = w;
......@@ -888,136 +818,71 @@ export class ShapeRect extends MySprite {
}
drawShape() {
this.ctx.fillStyle = this.fillColor;
this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class ShapeCircle extends MySprite {
fillColor = '#FF0000';
fillColor = "#FFFF00";
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) {
this.anchorX = this.anchorY = 0.5;
this.radius = r;
this.width = r * 2;
this.height = r * 2;
}
drawShape() {
switch(this.drawType){
case "stroke":
this.ctx.beginPath();
this.ctx.strokeStyle = this.strokeColor;
this.ctx.lineWidth = this.strokeLineWidth
this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian, this.counterclockwise);
this.ctx.stroke()
break;
default:
this.ctx.beginPath();
this.ctx.fillStyle = this.fillColor;
this.ctx.arc(0, 0, this.radius, 0, angleToRadian(360));
this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian);
this.ctx.shadowColor = this.shadowColor
this.ctx.shadowOffsetX = this.shadowOffsetX
this.ctx.shadowOffsetY = this.shadowOffsetY
this.ctx.fill();
break;
}
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 {
export class MyAnimation extends MySprite {
frameArr = [];
frameIndex = 0;
playFlag = false;
lastDateTime;
curDelay = 0;
loop = false;
playEndFunc;
delayPerUnit = 1;
......@@ -1026,7 +891,6 @@ export class MyAnimation extends MySprite {
reverseFlag = false;
addFrameByImg(img) {
const spr = new MySprite(this.ctx);
spr.init(img);
this._refreshSize(img);
......@@ -1040,10 +904,8 @@ export class MyAnimation extends MySprite {
}
addFrameByUrl(url) {
const spr = new MySprite(this.ctx);
spr.load(url).then(img => {
this._refreshSize(img);
});
spr.visible = false;
......@@ -1054,18 +916,15 @@ export class MyAnimation extends MySprite {
this.frameArr[this.frameIndex].visible = true;
}
_refreshSize(img: any) {
if (this.width < img.width) {
this.width = img.width;
_refreshSize(img) {
if (this.width < img["width"]) {
this.width = img["width"];
}
if (this.height < img.height) {
this.height = img.height;
if (this.height < img["height"]) {
this.height = img["height"];
}
}
play() {
this.playFlag = true;
this.lastDateTime = new Date().getTime();
......@@ -1075,13 +934,11 @@ export class MyAnimation extends MySprite {
this.playFlag = false;
}
replay() {
this.restartFlag = true;
this.play();
}
reverse() {
this.reverseFlag = !this.reverseFlag;
this.frameArr.reverse();
......@@ -1089,20 +946,18 @@ export class MyAnimation extends MySprite {
}
showAllFrame() {
for (const frame of this.frameArr ) {
frame.alpha = 1;
for (let i = 0; i < this.frameArr.length; i++) {
this.frameArr[i].alpha = 1;
}
}
hideAllFrame() {
for (const frame of this.frameArr) {
frame.alpha = 0;
for (let i = 0; i < this.frameArr.length; i++) {
this.frameArr[i].alpha = 0;
}
}
playEnd() {
this.playFlag = false;
this.curDelay = 0;
......@@ -1119,7 +974,7 @@ export class MyAnimation extends MySprite {
this.frameArr[this.frameIndex].visible = false;
}
this.frameIndex ++;
this.frameIndex++;
if (this.frameIndex >= this.frameArr.length) {
if (this.loop) {
this.frameIndex = 0;
......@@ -1127,21 +982,16 @@ export class MyAnimation extends MySprite {
this.restartFlag = false;
this.frameIndex = 0;
} else {
this.frameIndex -- ;
this.frameIndex--;
this.playEnd();
return;
}
}
this.frameArr[this.frameIndex].visible = true;
}
_updateDelay(delay) {
this.curDelay += delay;
if (this.curDelay < this.delayPerUnit) {
return;
......@@ -1151,7 +1001,9 @@ export class MyAnimation extends MySprite {
}
_updateLastDate() {
if (!this.playFlag) { return; }
if (!this.playFlag) {
return;
}
let delay = 0;
if (this.lastDateTime) {
......@@ -1165,18 +1017,18 @@ export class MyAnimation extends MySprite {
super.update($event);
this._updateLastDate();
}
}
// --------=========== util func =============-------------
export function tweenChange(item, obj, time = 0.8, callBack = null, easing = null, update = null) {
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) {
......@@ -1188,7 +1040,7 @@ export function tweenChange(item, obj, time = 0.8, callBack = null, easing = nul
tween.easing(easing);
}
if (update) {
tween.onUpdate( (a, b) => {
tween.onUpdate((a, b) => {
update(a, b);
});
}
......@@ -1197,11 +1049,13 @@ export function tweenChange(item, obj, time = 0.8, callBack = null, easing = nul
return tween;
}
export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = null) {
export function rotateItem(
item,
rotation,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000);
if (callBack) {
......@@ -1216,11 +1070,17 @@ export function rotateItem(item, rotation, time = 0.8, callBack = null, 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);
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(() => {
......@@ -1235,10 +1095,15 @@ export function scaleItem(item, scale, time = 0.8, callBack = null, easing = nul
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);
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(() => {
......@@ -1254,36 +1119,26 @@ export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null)
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(() => {
})
.onComplete(function() {})
.start();
}
export function hideItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha === 0) {
if (item.alpha == 0) {
return;
}
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.
.onComplete(() => {
.onComplete(function() {
if (callBack) {
callBack();
}
......@@ -1296,10 +1151,8 @@ export function hideItem(item, time = 0.8, callBack = null, easing = null) {
tween.start();
}
export function showItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha === 1) {
if (item.alpha == 1) {
if (callBack) {
callBack();
}
......@@ -1308,9 +1161,9 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) {
item.visible = true;
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.
.onComplete(() => {
.onComplete(function() {
if (callBack) {
callBack();
}
......@@ -1323,14 +1176,17 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) {
tween.start();
}
export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = null) {
export function alphaItem(
item,
alpha,
time = 0.8,
callBack = null,
easing = null
) {
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.
.onComplete(() => {
.onComplete(function() {
if (callBack) {
callBack();
}
......@@ -1343,14 +1199,11 @@ export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = nul
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)
.to({ alpha: 1, scale: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.onComplete(function() {
if (callBack) {
callBack();
}
......@@ -1363,97 +1216,103 @@ export function showStar(item, time = 0.8, callBack = null, easing = null) {
tween.start();
}
export function randomSortByArr(arr) {
const newArr = [];
const tmpArr = arr.concat();
while (tmpArr.length > 0) {
const randomIndex = Math.floor( tmpArr.length * Math.random() );
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;
return (radian * 180) / Math.PI;
// 角度 = 弧度 * 180 / Math.PI;
}
export function angleToRadian(angle) {
return angle * Math.PI / 180;
return (angle * Math.PI) / 180;
// 弧度= 角度 * Math.PI / 180;
}
export function getPosByAngle(angle, len) {
const radian = angle * Math.PI / 180;
const radian = (angle * Math.PI) / 180;
const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len;
return {x, y};
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; // 将弧度转换成角度
let angle = Math.floor((180 / (Math.PI / radina)) * 100) / 100; // 将弧度转换成角度
if (mx > px && my > py) {// 鼠标在第四象限
if (mx > px && my > py) {
// 鼠标在第四象限
angle = 180 - angle;
}
if (mx === px && my > py) {// 鼠标在y轴负方向上
if (mx === px && my > py) {
// 鼠标在y轴负方向上
angle = 180;
}
if (mx > px && my === py) {// 鼠标在x轴正方向上
if (mx > px && my === py) {
// 鼠标在x轴正方向上
angle = 90;
}
if (mx < px && my > py) {// 鼠标在第三象限
if (mx < px && my > py) {
// 鼠标在第三象限
angle = 180 + angle;
}
if (mx < px && my === py) {// 鼠标在x轴负方向
if (mx < px && my === py) {
// 鼠标在x轴负方向
angle = 270;
}
if (mx < px && my < py) {// 鼠标在第二象限
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) {
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) {
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};
const obj = { r, a };
item._circleAngle = a;
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) {
tween.onComplete(() => {
......@@ -1464,14 +1323,13 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer =
tween.easing(easing);
}
tween.onUpdate( (item, progress) => {
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);
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;
......@@ -1482,12 +1340,10 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer =
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) );
const len = Math.sqrt(Math.pow(_x, 2) + Math.pow(_y, 2));
return len;
}
......@@ -1502,29 +1358,6 @@ export function delayCall(callback, second) {
.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;
......@@ -1532,11 +1365,7 @@ export function getMinScale(item, maxLen) {
return minS;
}
export function jelly(item, time = 0.7) {
if (item.jellyTween) {
TWEEN.remove(item.jellyTween);
}
......@@ -1552,10 +1381,16 @@ export function jelly(item, time = 0.7) {
return;
}
const data = arr[index];
const t = tweenChange(item, {scaleX: data[0], scaleY: data[1]}, data[2], () => {
index ++;
const t = tweenChange(
item,
{ scaleX: data[0], scaleY: data[1] },
data[2],
() => {
index++;
run();
}, TWEEN.Easing.Sinusoidal.InOut);
},
TWEEN.Easing.Sinusoidal.InOut
);
item.jellyTween = t;
};
......@@ -1564,20 +1399,24 @@ export function jelly(item, time = 0.7) {
[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],
[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 ++) {
/**
* 烟花爆炸效果动画
* @param img 颗粒的图片
* @param pos 爆点的坐标
* @param parent 必须传一个父类
*/
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();
particle.init(img);
particle.x = pos.x;
......@@ -1587,8 +1426,8 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen
const randomR = 360 * Math.random();
particle.rotation = randomR;
const randomS = 0.3 + Math.random() * 0.7;
particle.setScaleXY(randomS * 0.3);
const randomS = 0.5 + Math.random() * 0.5;
particle.setScaleXY(randomS);
const randomX = Math.random() * 20 - 10;
particle.x += randomX;
......@@ -1596,39 +1435,23 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen
const randomY = Math.random() * 20 - 10;
particle.y += randomY;
const randomL = minLen + Math.random() * (maxLen - minLen);
const randomL = minLen + Math.random() * maxLen;
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);
moveItem(
particle,
particle.x + randomT.x,
particle.y + randomT.y,
0.4,
() => {},
TWEEN.Easing.Exponential.Out
);
scaleItem(particle, 0, 0.6, () => {});
}
}
export function shake(item, time = 0.5, callback = null, rate = 1) {
if (item.shakeTween) {
return;
}
......@@ -1640,37 +1463,104 @@ export function shake(item, time = 0.5, callback = null, rate = 1) {
const baseY = item.y;
const easing = TWEEN.Easing.Sinusoidal.InOut;
const move4 = () => {
moveItem(item, baseX, baseY, time / 4, () => {
moveItem(
item,
baseX,
baseY,
time / 4,
() => {
item.shakeTween = false;
if (callback) {
callback();
}
}, easing);
},
easing
);
};
const move3 = () => {
moveItem(item, baseX + offX / 4, baseY + offY / 4, time / 4, () => {
moveItem(
item,
baseX + offX / 4,
baseY + offY / 4,
time / 4,
() => {
move4();
}, easing);
},
easing
);
};
const move2 = () => {
moveItem(item, baseX - offX / 4 * 3, baseY - offY / 4 * 3, time / 4, () => {
moveItem(
item,
baseX - (offX / 4) * 3,
baseY - (offY / 4) * 3,
time / 4,
() => {
move3();
}, easing);
},
easing
);
};
const move1 = () => {
moveItem(item, baseX + offX, baseY + offY, time / 7.5, () => {
moveItem(
item,
baseX + offX,
baseY + offY,
time / 8,
() => {
move2();
}, easing);
},
easing
);
};
move1();
}
// --------------- 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/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/font/BRLNSDB.TTF") ;
}
@font-face
{
font-family: 'RoundedBold';
src: url("../../assets/font/ArialRoundedBold.otf") ;
}
@font-face{
font-family: 'BRLNSB_1';
src: url("../../assets/font/BerlinSansFB/BRLNSB_1.TTF") ;
}
@font-face{
font-family: 'BerlinSansFBDemi-Bold';
src: url("../../assets/font/BerlinSansFB/BRLNSDB_1.TTF") ;
}
@font-face{
font-family: 'BRLNSR_1';
src: url("../../assets/font/BerlinSansFB/BRLNSR_1.TTF") ;
}
@font-face{
font-family: 'GOTHIC_1';
src: url("../../assets/font/CenturyGothic/GOTHIC_1.TTF") ;
}
@font-face{
font-family: 'GOTHICB_1';
src: url("../../assets/font/CenturyGothic/GOTHICB_1.TTF") ;
}
@font-face{
font-family: 'GOTHICBI_1';
src: url("../../assets/font/CenturyGothic/GOTHICBI_1.TTF") ;
}
@font-face{
font-family: 'GOTHICI_1';
src: url("../../assets/font/CenturyGothic/GOTHICI_1.TTF") ;
}
@font-face{
font-family: 'MMTextBook';
src: url("../../assets/font/MMTextBook/MMTextBook.otf") ;
}
@font-face{
font-family: 'MMTextBook-Bold';
src: url("../../assets/font/MMTextBook/MMTextBook-Bold.otf") ;
}
@font-face{
font-family: 'MMTextBook-BoldItalic';
src: url("../../assets/font/MMTextBook/MMTextBook-BoldItalic.otf") ;
}
@font-face{
font-family: 'MMTextBook-Italic';
src: url("../../assets/font/MMTextBook/MMTextBook-Italic.otf") ;
}
import {Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener} from '@angular/core';
import {
Component,
ElementRef,
ViewChild,
OnInit,
Input,
OnDestroy,
HostListener
} from "@angular/core";
import {
MySprite,
getMinScale,
ShapeRect,
ShapeCircle,
tweenChange,
randomSortByArr,
Label,
MySprite, tweenChange,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem,
hideItem,
showItem,
ShapeRectNew,
scaleItem,
showBlingBling,
waterWave,
jelly
} from "./Unit";
import { localImages, localAudios } from "./resources";
import { Cartoon } from './Cartoon'
import { Subject } from "rxjs";
import { debounceTime, map, takeWhile } from "rxjs/operators";
import * as _ from "lodash";
import TWEEN from "@tweenjs/tween.js";
const defauleFormData = {
sex:"male"
}
} from './Unit';
import {res, resAudio} from './resources';
const zIndexMap = {
background: -1001,
smallGrass: -1000,
cylinder: 100,
grass:10000,
monkey:500,
card:1000
}
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
@Component({
selector: "app-play",
templateUrl: "./play.component.html",
styleUrls: ["./play.component.scss"]
})
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_enableMapDown = true; // 触摸使能
g_enableMapUp = true; // 抬起使能
g_enableMapMove = true; // 移动ss使能
g_canvasLeft;
g_canvasTop;
g_animationId: any;
g_mapScale = 1; // 缩放比例
g_KEY = "DataKey_East_L215";
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;
// ------------------------------------
// ------------ 私有数据 ------------
m_mapDownQueue = {} //按下事件处理队列
m_mapUpQueue = {} //抬起事件处理队列
m_mapMoveArray = [] //移动事件处理队列
m_mapMoveObject = []
m_endPageArr;
m_showPetalFlag;
m_elementPetalArr;
m_showElementPetalFlag;
m_PetalImage = "petal_" // 飘落动画
m_renderArr // 渲染队列
m_renderObject = [];
m_defaultZindex = 0;
m_setTimeoutIDs = [];
m_setIntervalIDs = [];
// ------------------------------------
// ------------ 游戏逻辑数据 ------------
m_allCardIds = []
m_runIntervalId = null
m_runStatus = false;
m_mouseInRunway = false;
// ------------------------------------
// ------------ 消息 ------------
// ------------------------------------
// ------------ 调试变量 ------------
g_EnableStageRuler = true; // 使能舞台背景格尺
g_ForceChangeDefaultRole = false // 强制当前角色为默认角色
g_EnableTestSendEvent = false // 发送模拟Web数据
// ------------------------------------
// 当数据加载完毕后,执行
systemReady(){
this.initGame()
}
// 屏幕尺寸变化后执行
handleScreenResize(){
this.initSystem();
this.restartGame()
}
// 映射预加载图片[网路]资源 返回包含图片路径的数组
mapToImageArray(contentObj){
let array = []
return array
}
@Component({
selector: 'app-play',
templateUrl: './play.component.html',
styleUrls: ['./play.component.css']
})
export class PlayComponent implements OnInit, OnDestroy {
// 映射预加载音频[网路]资源 返回包含音频路径的数组
mapToAduioArray(contentObj){
let array = []
return array
}
@ViewChild('canvas', {static: true }) canvas: ElementRef;
@ViewChild('wrap', {static: true }) wrap: ElementRef;
restartGame() {
this.cleanGameVar()
this.initGame()
}
// 数据
data;
ctx;
// ------------------------------------------------------------------------------
// 游戏核心处理区
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
initGame(){
this.initBackground();
this.initTitle()
this.initTable()
this.initCardContainer()
this.initCardRunway()
this.initCards()
this.initLights()
this.cardRunControl(true)
}
canvasWidth = 1280; // canvas实际宽度
canvasHeight = 720; // canvas实际高度
cleanGameVar(){
this.stopAllInterval();
this.stopAllTimeout()
this.g_cartoon.stopAllAudio()
this.m_allCardIds = []
this.cardRunControl(false)
}
canvasBaseW = 1280; // canvas 资源预设宽度
canvasBaseH = 720; // canvas 资源预设高度
endGame(){
mx; // 点击x坐标
my; // 点击y坐标
}
initBackground(){
let element = this.g_cartoon.createCartoonElementImage('my-background', "bg-background", this.g_canvasWidth, this.g_canvasHeight, this.g_canvasWidth/2, this.g_canvasHeight/2,)
this.subscribeMapMoveEvent('my-background', ()=>{
if(this.m_mouseInRunway){
this.cardRunControl(true)
}
this.m_mouseInRunway = false;
this.g_enableMapMove = true;
})
this.render(element.ref)
}
// 资源
rawImages = new Map(res);
rawAudios = new Map(resAudio);
initTitle(){
let titleText = "Drag and drop games"
let element = this.g_cartoon.createCartoonElementImage('title', "bg_title", 576*this.g_mapScale, 66*this.g_mapScale, this.g_canvasWidth/2, this.g_cartoon.getOrigin().y+48*this.g_mapScale)
let title = new Label()
title.text = titleText
title.fontColor = "#fffc1d";
title.fontName = "BerlinSansFBDemi-Bold";
title.fontSize = 58
title.x = -288
element.ref.addChild(title)
this.render(element.ref)
}
images = new Map();
initCardRunway(){
let element = this.g_cartoon.createCartoonElementImageFunc('card-runway', "bg_card_runway", (w,h)=>{
return {
sx: this.g_canvasWidth/w,
sy: 300*this.g_mapScale/h
}
}, (w,h)=>{
return {
x: this.g_canvasWidth/2,
y: this.g_cartoon.getOrigin().y+ (h/2)*this.g_mapScale + 96*this.g_mapScale
}
})
animationId: any;
winResizeEventStream = new Subject();
this.subscribeMapMoveEvent('card-runway', ()=>{
if(!this.m_mouseInRunway){
this.cardRunControl(false)
}
this.m_mouseInRunway = true;
this.g_enableMapMove = true;
return true;
},-1)
audioObj = {};
this.render(element.ref)
}
renderArr;
mapScale = 1;
initTable(){
let element = this.g_cartoon.createCartoonElementImageFunc('desk', "desk", (w,h)=>{
return {
sx: this.g_canvasWidth/w,
sy: 228*this.g_mapScale/h
}
}, (w,h)=>{
return {
x: this.g_canvasWidth/2,
y: this.g_cartoon.getOrigin().y+ (h/2)*this.g_mapScale + 492*this.g_mapScale
}
})
this.render(element.ref)
}
canvasLeft;
canvasTop;
initCardContainer(){
let element = this.g_cartoon.createCartoonElementImageFunc('card-container', "dish", (w,h)=>{
return {
sx: 658*this.g_mapScale/w,
sy: 228*this.g_mapScale/h
}
}, (w,h)=>{
return {
x: this.g_canvasWidth/2,
y: this.g_cartoon.getOrigin().y+ (h/2)*this.g_mapScale + 481*this.g_mapScale
}
})
this.render(element.ref)
}
saveKey = 'test_0011';
initCards(){
let boundingBox = this.g_cartoon.getCartoonElement('card-runway').ref.getBoundingBox()
let cardWidth = 251*this.g_mapScale
let cardNumber = Math.ceil(this.g_canvasWidth/cardWidth);
for(let index=0; index<cardNumber; index++){
this.render(this.createCard(index,index*cardWidth,boundingBox.y).ref)
}
}
createCard(index,x,y){
this.m_allCardIds.push(`card-bckground-${index}`)
let element = this.g_cartoon.createCartoonElementImageFunc(`card-bckground-${index}`, "bg_card", (w,h)=>{
return {
sx: 230*this.g_mapScale/w,
sy: 209*this.g_mapScale/h
}
}, (w,h)=>{
return {
x: x + (w/2)*this.g_mapScale + 21*this.g_mapScale,
y: y + 150*this.g_mapScale
}
})
btnLeft;
btnRight;
pic1;
pic2;
let imageContainer= new MySprite()
imageContainer.init(this.g_cartoon.images.get("card"))
imageContainer.setScaleXY(180/imageContainer.width)
element.ref.addChild(imageContainer)
canTouch = true;
let textContainer= new MySprite()
textContainer.init(this.g_cartoon.images.get("text_container"))
textContainer.setScaleXY(150/textContainer.width)
let textContent = new Label()
textContent.text = "AVA"// + index + "This is for test"
textContent.fontColor = "#e05e14";
textContent.fontName = "BerlinSansFBDemi-Bold";
textContent.maxSingalLineWidth = 170*this.g_mapScale
textContent.x = textContent.width/2
textContent.fontSize = 50
textContainer.addChild(textContent)
textContainer.x = -textContainer.width/4
// textContainer.y = -textContainer.height/2
element.ref.addChild(textContainer)
curPic;
@HostListener('window:resize', ['$event'])
onResize(event) {
this.winResizeEventStream.next();
}
ngOnInit() {
this.data = {};
return element;
}
// 获取数据
const getData = (<any> window).courseware.getData;
getData((data) => {
cardRunControl(status){
let step = 1*this.g_mapScale;
if(status){
this.m_runIntervalId = setInterval(()=>{
this.m_allCardIds.forEach((id)=>{
this.g_cartoon.getCartoonElementRef(id).x -= step
})
this.m_runStatus = true;
},10)
}else{
clearInterval(this.m_runIntervalId)
this.m_runStatus = false;;
}
}
if (data && typeof data == 'object') {
this.data = data;
initLights(){
this.g_cartoon.getCartoonElement('card-runway').ref.addChild(this.createLights(0,0).ref)
this.g_cartoon.getCartoonElement('card-runway').ref.addChild(this.createLights(1,0).ref)
}
// console.log('data:' , data);
// 初始化 各事件监听
this.initListener();
createLights(line, row){
let pos_y = [
-126,126
]
let element = this.g_cartoon.createCartoonElementImage(`water-light-${line}-${row}`, "light-1", 48, 48, 0, pos_y[line])
return element;
}
// 若无数据 则为预览模式 需要填充一些默认数据用来显示
this.initDefaultData();
// 初始化 音频资源
this.initAudio();
// 初始化 图片资源
this.initImg();
// 开始预加载资源
this.load();
}, this.saveKey);
}
ngOnDestroy() {
window['curCtx'] = null;
window.cancelAnimationFrame(this.animationId);
}
load() {
// 预加载资源
this.loadResources().then(() => {
window["air"].hideAirClassLoading(this.saveKey, this.data);
this.init();
this.update();
});
}
init() {
this.initCtx();
this.initData();
this.initView();
}
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');
this.canvas.nativeElement.width = this.canvasWidth;
this.canvas.nativeElement.height = this.canvasHeight;
window['curCtx'] = this.ctx;
}
updateItem(item) {
if (item) {
item.update();
}
}
updateArr(arr) {
if (!arr) {
return;
}
for (let i = 0; i < arr.length; i++) {
arr[i].update(this);
}
}
......@@ -169,204 +370,344 @@ export class PlayComponent implements OnInit, OnDestroy {
initListener() {
this.winResizeEventStream
.pipe(debounceTime(500))
.subscribe(data => {
this.renderAfterResize();
});
// ---------------------------------------------
const setParentOffset = () => {
const rect = this.canvas.nativeElement.getBoundingClientRect();
this.canvasLeft = rect.left;
this.canvasTop = rect.top;
};
const setMxMyByTouch = (event) => {
if (event.touches.length <= 0) {
return;
// --------------------------------------------------
// -------------- Template function ---------------
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
//
// _________
// / /.
// .-------------. /_________/ |
// / / | | | |
// /+============+\ | | |====| | |
// ||C:\> || | | | |
// || || | | |====| | |
// || || | | ___ | |
// || || | | |166| | |
// || ||/@@@ | --- | |
// \+============+/ @ |_________|./.
// @ .. ....'
// ..................@ __.'.' ''
// /oooooooooooooooo// ///
// /................// /_/
// ------------------
//
// --------------------------------------------------
@ViewChild("canvas") canvas: ElementRef;
@ViewChild("wrap") wrap: ElementRef;
@HostListener("window:resize", ["$event"])
onResize(event) {
this.g_winResizeEventStream.next();
}
if (this.canvasLeft == null) {
setParentOffset();
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 = {};
}
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;
};
// ---------------------------------------------
if (!this.g_data.contentObj) {
this.g_data.contentObj = {};
this.g_formData = {};
}
this.initDefaultData();
this.initAudio();
this.initImg();
let firstTouch = true;
// 预加载资源
this.g_cartoon.loadResources().then(() => {
window["air"].hideAirClassLoading(this.g_KEY, this.g_data);
this.initSystem();
this.update();
this.systemReady()
});
const touchDownFunc = (e) => {
if (firstTouch) {
firstTouch = false;
removeMouseListener();
this.initListener();
}, this.g_KEY);
}
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 (firstTouch) {
firstTouch = false;
removeTouchListener();
// ----------------------------------
// 初始化默认数据
// ----------------------------------
initDefaultData() {
if ( Object.keys(this.g_formData).length===0 ) {
// console.log("Init default form data")
this.g_formData = defauleFormData;
}else if(!this.g_formData.sex){
this.g_formData = defauleFormData;
}
}
setMxMyByMouse(e);
this.mapDown(e);
};
const mouseMoveFunc = (e) => {
setMxMyByMouse(e);
this.mapMove(e);
};
const mouseUpFunc = (e) => {
setMxMyByMouse(e);
this.mapUp(e);
};
const element = this.canvas.nativeElement;
// ----------------------------------
// 初始化音乐
// ----------------------------------
initAudio() {
const contentObj = this.g_formData;
if (!contentObj) {
return;
}
// 添加用户上传音效
let images:Array<string> = this.mapToAduioArray(contentObj)
images.forEach(image => {
this.g_cartoon.addAudio( image, image );
});
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);
};
// 添加本地音效
for( var key in localAudios ){
this.g_cartoon.addAudio( key, localAudios[key] );
}
}
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);
// ----------------------------------
// 初始化图片
// ----------------------------------
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] );
}
}
mapDown(event) {
if (!this.g_enableMapDown) {
return;
}
for(let cartoonID in this.m_mapDownQueue){
if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(cartoonID))) {
this.g_enableMapDown = false;
this.m_mapDownQueue[cartoonID]();
}
}
}
mapMove(event) {
// console.log(this.g_clickX, this.g_clickY)
let myStopPropagation = false;
if (!this.g_enableMapMove) {
return;
}
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;
}
}
}
})
}
addMouseListener();
addTouchListener();
mapUp(event) {
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]();
}
}
}
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);
}
playAudio(key, now = false, callback = null) {
const audio = this.audioObj[key];
if (audio) {
if (now) {
audio.pause();
audio.currentTime = 0;
updateItem(item) {
if (item) {
item.update();
}
}
if (callback) {
audio.onended = () => {
callback();
};
updateArr(arr) {
if (!arr) {
return;
}
audio.play();
for (let i = 0; i < arr.length; i++) {
arr[i].update(this);
}
}
initListener() {
this.g_winResizeEventStream.pipe(debounceTime(500)).subscribe(data => {
this.renderAfterResize();
});
loadResources() {
const pr = [];
this.rawImages.forEach((value, key) => {// 预加载图片
if (this.IsPC()) {
this.canvas.nativeElement.addEventListener("mousedown", event => {
setMxMyByMouse(event);
this.mapDown(event);
});
const p = this.preload(value)
.then(img => {
this.images.set(key, img);
})
.catch(err => console.log(err));
this.canvas.nativeElement.addEventListener("mousemove", event => {
setMxMyByMouse(event);
this.mapMove(event);
});
pr.push(p);
this.canvas.nativeElement.addEventListener("mouseup", event => {
setMxMyByMouse(event);
this.mapUp(event);
});
this.rawAudios.forEach((value, key) => {// 预加载音频
const setMxMyByMouse = event => {
this.g_clickX = event.offsetX;
this.g_clickY = event.offsetY;
};
} else {
this.canvas.nativeElement.addEventListener("touchstart", event => {
setMxMyByTouch(event);
this.mapDown(event);
});
const a = this.preloadAudio(value)
.then(() => {
// this.images.set(key, img);
})
.catch(err => console.log(err));
this.canvas.nativeElement.addEventListener("touchmove", event => {
setMxMyByTouch(event);
this.mapMove(event);
});
pr.push(a);
this.canvas.nativeElement.addEventListener("touchend", event => {
setMxMyByTouch(event);
this.mapUp(event);
});
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;
this.canvas.nativeElement.addEventListener("touchcancel", event => {
setMxMyByTouch(event);
this.mapUp(event);
});
const setMxMyByTouch = event => {
if (event.touches.length <= 0) {
return;
}
preloadAudio(url) {
return new Promise((resolve, reject) => {
const audio = new Audio();
audio.oncanplay = (a) => {
resolve();
};
audio.onerror = () => {
reject();
};
audio.src = url;
audio.load();
});
if (this.g_canvasLeft == null) {
setParentOffset();
}
this.g_clickX = event.touches[0].pageX - this.g_canvasLeft;
this.g_clickY = event.touches[0].pageY - this.g_canvasTop;
};
renderAfterResize() {
this.canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight;
this.init();
const setParentOffset = () => {
const rect = this.canvas.nativeElement.getBoundingClientRect();
this.g_canvasLeft = rect.left;
this.g_canvasTop = rect.top;
};
}
}
showArr(arr) {
if (!arr) {
return;
}
for (let i = 0; i < arr.length; i++) {
arr[i].visible = true;
}
}
hideArr(arr) {
if (!arr) {
return;
}
for (let i = 0; i < arr.length; i++) {
arr[i].visible = false;
}
}
IsPC() {
if (window["ELECTRON"]) {
return false; // 封装客户端标记
}
if (
document.body.ontouchmove !== undefined &&
document.body.ontouchmove !== undefined
) {
return false;
} else {
return true;
}
}
renderAfterResize() {
this.g_canvasWidth = this.wrap.nativeElement.clientWidth;
this.g_canvasHeight = this.wrap.nativeElement.clientHeight;
this.update();
this.handleScreenResize()
}
checkClickTarget(target) {
if (!target) {
return false;
}
const rect = target.getBoundingBox();
if (this.checkPointInRect(this.mx, this.my, rect)) {
if (this.checkPointInRect(this.g_clickX, this.g_clickY, rect)) {
return true;
}
return false;
}
getWorlRect(target) {
getWorlRect(target) {
let rect = target.getBoundingBox();
if (target.parent) {
const pRect = this.getWorlRect(target.parent);
rect.x += pRect.x;
rect.y += pRect.y;
......@@ -374,6 +715,7 @@ export class PlayComponent implements OnInit, OnDestroy {
return rect;
}
checkPointInRect(x, y, rect) {
if (x >= rect.x && x <= rect.x + rect.width) {
if (y >= rect.y && y <= rect.y + rect.height) {
......@@ -384,296 +726,431 @@ export class PlayComponent implements OnInit, OnDestroy {
}
addUrlToAudioObj(key, url = null, vlomue = 1, loop = false, callback = null) {
const audioObj = this.audioObj;
if (url == null) {
url = key;
getPosByAngle(angle, len) {
const radian = (angle * Math.PI) / 180;
const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len;
return { x, y };
}
this.rawAudios.set(key, url);
const audio = new Audio();
audio.src = url;
audio.load();
audio.loop = loop;
audio.volume = vlomue;
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;
}
audioObj[key] = audio;
if (callback) {
audio.onended = () => {
callback();
};
subscribeMapDownEvent(id,callback){
this.m_mapDownQueue[id] = callback
}
subscribeMapUpEvent(id,callback){
this.m_mapUpQueue[id] = callback
}
addUrlToImages(url) {
this.rawImages.set(url, url);
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, -999999)
this.g_stage = image
}
/**
* 添加默认数据 便于无数据时的展示
*/
initDefaultData() {
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)
})
}
if (!this.data.pic_url) {
this.data.pic_url = 'assets/play/default/pic.jpg';
this.data.pic_url_2 = 'assets/play/default/pic.jpg';
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) => {
callback(JSON.parse(data))
next && next();
});
}
randomArray_shuffle(array) {
var input = array;
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;
}
/**
* 添加预加载图片
*/
initImg() {
paginationArray(pageNo, pageSize, array) {
var offset = (pageNo - 1) * pageSize;
return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
}
this.addUrlToImages(this.data.pic_url);
this.addUrlToImages(this.data.pic_url_2);
stopAllTimeout(){
this.m_setTimeoutIDs.forEach(id=>clearTimeout(id))
this.m_setTimeoutIDs = []
}
stopAllInterval(){
this.m_setIntervalIDs.forEach(id=>clearInterval(id))
this.m_setIntervalIDs = []
}
/**
* 添加预加载音频
*/
initAudio() {
// 音频资源
this.addUrlToAudioObj(this.data.audio_url);
this.addUrlToAudioObj(this.data.audio_url_2);
// 音效
this.addUrlToAudioObj('click', this.rawAudios.get('click'), 0.3);
}
/**
* 初始化数据
*/
initData() {
const sx = this.canvasWidth / this.canvasBaseW;
const sy = this.canvasHeight / this.canvasBaseH;
const s = Math.min(sx, sy);
this.mapScale = s;
// this.mapScale = sx;
// this.mapScale = sy;
this.renderArr = [];
}
/**
* 初始化试图
*/
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;
}
// --------------------------------------------------
// -------------- Template function ---------------
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
//
// .-~~~~~~~~~-._ _.-~~~~~~~~~-.
// __.' ~. .~ `.__
// .'// \./ \\`.
// .'// | \\`.
// .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`.
// .'//.-" `-. | .-' "-.\\`.
// .'//______.============-.. \ | / ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
// --------------------------------------------------
// showParticle( element_id ) 泡泡效果
// --------------------------------------------------
// showEndPatal() / stopEndPatal() 花瓣飘落结束动画
// --------------------------------------------------
// showCorrectPatal() 指定元素上面飘花
// --------------------------------------------------
// convertPercentToRadian() 将百分比转换为弧长 第一个参数是百分比,第二个参数是方向 true为逆时针,false为顺时针。用于ShapeCircle换圆弧
// --------------------------------------------------
// movePaoWuxian() 元素抛物线跳
// --------------------------------------------------
// showJellyAnimation()------------------------------
// showBlingStar()----------------------显示星星效果--
// --------------------------------------------------
btnLeftClicked() {
this.lastPage();
// 泡泡
showParticle(card) {
let myCard = this.g_cartoon.getCartoonElementRelativePosition(card.id)
showPopParticle(this.g_cartoon.images.get("_bubble"), { x: myCard.x , y: myCard.y }, this.g_stage);
}
btnRightClicked() {
this.nextPage();
// 选择正确动画
showCorrectPatal(card_id, showTime) {
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = true;
this.addCorrectPetal(card_id);
setTimeout(()=>{
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = false;
},showTime)
}
stopAllCorrectPatal(){
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = false;
}
lastPage() {
if (this.curPic == this.pic1) {
addCorrectPetal(card_id) {
if (!this.m_showElementPetalFlag) {
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.pic1;
});
}
const id = Math.ceil(Math.random() * 3);
petal.init(this.g_cartoon.images.get(this.m_PetalImage + id));
nextPage() {
const randomS = (Math.random() * 0.4 + 0.6) * this.g_mapScale * 0.5;
petal.setScaleXY(randomS);
if (this.curPic == this.pic2) {
return;
}
const randomR = Math.random() * 360;
petal.rotation = randomR;
this.canTouch = false;
const randomX = Math.random() * element.ref.width * this.g_mapScale;
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;
});
}
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);
pic1Clicked() {
this.playAudio(this.data.audio_url);
}
const randomT = 1 + Math.random() * 2;
petal["time"] = randomT;
pic2Clicked() {
this.playAudio(this.data.audio_url_2);
let randomTR = 360 * Math.random(); // - 180;
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);
}
mapDown(event) {
if (!this.canTouch) {
return;
// 结束动画花瓣飘落
showEndPatal() {
this.m_endPageArr = [];
this.m_showPetalFlag = true;
this.addPetal();
}
if ( this.checkClickTarget(this.btnLeft) ) {
this.btnLeftClicked();
return;
stopEndPatal() {
this.m_endPageArr = [];
this.m_showPetalFlag = false;
}
if ( this.checkClickTarget(this.btnRight) ) {
this.btnRightClicked();
addPetal() {
if (!this.m_showPetalFlag) {
return;
}
if ( this.checkClickTarget(this.pic1) ) {
this.pic1Clicked();
return;
const petal = this.getPetal();
this.m_endPageArr.push(petal);
moveItem(
petal,
petal.x,
this.g_canvasHeight + petal.height * petal.scaleY,
petal["time"],
() => {
removeItemFromArr(this.m_endPageArr, petal);
}
if ( this.checkClickTarget(this.pic2) ) {
this.pic2Clicked();
return;
);
rotateItem(petal, petal["tr"], petal["time"]);
setTimeout(() => {
this.addPetal();
}, 100);
}
}
getPetal() {
const petal = new MySprite(this.g_ctx);
mapMove(event) {
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);
mapUp(event) {
const randomR = Math.random() * 360;
petal.rotation = randomR;
}
const randomX = Math.random() * this.g_canvasWidth;
petal.x = randomX;
petal.y = (-petal.height / 2) * petal.scaleY;
const randomT = 2 + Math.random() * 5;
petal["time"] = randomT;
let randomTR = 360 * Math.random(); // - 180;
if (Math.random() < 0.5) {
randomTR *= -1;
}
petal["tr"] = randomTR;
update() {
return petal;
}
// ----------------------------------------------------------
this.animationId = window.requestAnimationFrame(this.update.bind(this));
// 清除画布内容
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
// tween 更新动画
TWEEN.update();
// ----------------------------------------------------------
showJellyAnimation(element_id){
let element = this.g_cartoon.getCartoonElement(element_id).ref
tweenChange(element,{ scaleX: this.g_mapScale * 1.1 , scaleY: this.g_mapScale * 1.1 }, 0.1, ()=>{
tweenChange(element,{ scaleX: this.g_mapScale * 0.9 , scaleY: this.g_mapScale * 0.9 }, 0.1, ()=>{
tweenChange(element,{ scaleX: this.g_mapScale , scaleY: this.g_mapScale }, 0.1 )
})
})
}
showShakeAnimation(element_id){
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 )
})
})
}
this.updateArr(this.renderArr);
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){
let rect = element.getBoundingBox()
showBlingBling(this.g_cartoon.images.get('_star'), rect, element, 0.5, 1, 0.08, 2);
setTimeout(()=>{
showBlingBling(this.g_cartoon.images.get('_star'), rect, element, 0.5, 1, 0.08, 1.8);
},200)
setTimeout(()=>{
showBlingBling(this.g_cartoon.images.get('_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);
}
}
\ No newline at end of file
}
const res = [
const localImages = {
'_bg_1280_720_Ruler': 'assets/default/images/1280_720_Ruler.png',
'_bg_240_180': 'assets/default/images/bg_240_180.png',
'_bg_453_251': 'assets/default/images/bg_453_251.png',
'_bg_1280_222': 'assets/default/images/bg_1280_222.png',
'_bg_1280_720': 'assets/default/images/bg_1280_720.png',
'_bg_200_200': 'assets/default/images/bg_200_200.png',
'_bg_30_30': 'assets/default/images/bg_30_30.png',
'_bg_500_600': 'assets/default/images/bg_500_600.png',
'_bg_50_50': 'assets/default/images/bg_50_50.png',
'_bg_75_50': 'assets/default/images/bg_75_50.png',
'_bg_75_50_black': 'assets/default/images/bg_75_50_black.png',
'_flag': 'assets/default/images/flag.png',
'_go': 'assets/default/images/go.png',
'_header': 'assets/default/images/header.png',
'_ready': 'assets/default/images/ready.png',
'_replay': 'assets/default/images/replay.png',
'_scrap-pic-1': 'assets/default/images/scrap-pic-1.png',
'_scrap-pic-2': 'assets/default/images/scrap-pic-2.png',
'_scrap-pic-3': 'assets/default/images/scrap-pic-3.png',
'_sm-pic-1': 'assets/default/images/sm-pic-1.png',
'_sm-pic-2': 'assets/default/images/sm-pic-2.png',
'_sm-pic-3': 'assets/default/images/sm-pic-3.png',
'_sm-pic-4': 'assets/default/images/sm-pic-4.png',
'_star': 'assets/default/images/star.png',
'_bubble': 'assets/default/images/bubble.png',
// ['bg', "assets/play/bg.jpg"],
['btn_left', "assets/play/btn_left.png"],
['btn_right', "assets/play/btn_right.png"],
// ['text_bg', "assets/play/text_bg.png"],
'bg-background': 'assets/play/bg-background.png',
'box': 'assets/play/box.png',
'btn-go': 'assets/play/btn-go.png',
'btn-ok': 'assets/play/btn-ok.png',
'card-highlight': 'assets/play/card-highlight.png',
'card': 'assets/play/card.png',
'dish-shaodw': 'assets/play/dish-shaodw.png',
'dish': 'assets/play/dish.png',
'desk': 'assets/play/desk.png',
'light-1': 'assets/play/light-1.png',
'light-2': 'assets/play/light-2.png',
'bg_title': 'assets/play/bg_title.png',
'bg_card': 'assets/play/bg_card.png',
'bg_card_runway': 'assets/play/bg_card_runway.png',
'text_container': 'assets/play/text_container-1.png'
};
];
const localAudios = {
'sm-back': "assets/default/audio/sm-back.mp3",
'sm-display': "assets/default/audio/sm-display.mp3",
'sm-wrong': "assets/default/audio/sm-wrong.mp3",
'sm-win': "assets/default/audio/sm-win.mp3",
'sm-in': "assets/default/audio/sm-in.mp3",
'sm-out': "assets/default/audio/sm-out.mp3",
'sm-click': "assets/default/audio/sm-click.mp3",
'sm-start': "assets/default/audio/sm-start.mp3",
'sm-correct': 'assets/default/audio/sm-correct.mp3',
'sm-star': "assets/default/audio/sm-star.mp3",
'sm-choice-complete': 'assets/default/audio/sm-choice-complete.mp3',
'sm-choice-correct': 'assets/default/audio/sm-choice-correct.mp3',
'sm-choice-error': 'assets/default/audio/sm-choice-error.mp3',
'sm-choice-in': 'assets/default/audio/sm-choice-in.mp3',
'sm-choice-show-answer': 'assets/default/audio/sm-choice-show-answer.mp3',
'sm-choice-timeup-0': 'assets/default/audio/sm-choice-timeup-0.mp3',
'sm-choice-timeup-3': 'assets/default/audio/sm-choice-timeup-3.mp3',
'sm-go': 'assets/default/audio/sm-go.mp3',
'sm-ready': 'assets/default/audio/sm-ready.mp3',
'change': 'assets/audio/change.mp3',
'selected': 'assets/audio/selected.mp3',
};
const resAudio = [
['click', "assets/play/music/click.mp3"],
];
export {res, resAudio};
export {localImages, localAudios};
@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 =[]
for root, dirs, files in os.walk(file_dir):
fileList = files
return fileList
fileList = file_name(os.path.abspath('.'))
f = open('filename.txt', 'w')
for fn in fileList:
if fn.split(".")[0] != "creatJsonProfile":
f.write("'" + fn.split(".")[0] + "': 'assets/audio/" + fn + "',\n")
f.close()
\ No newline at end of file
import os
import json
def file_name(file_dir):
fileList =[]
for root, dirs, files in os.walk(file_dir):
fileList = files
return fileList
fileList = file_name(os.path.abspath('.'))
f = open('filename.txt', 'w')
for fn in fileList:
if fn.split(".")[0] != "creatJsonProfile":
f.write("'" + fn.split(".")[0] + "': 'assets/play/" + fn + "',\n")
f.close()
\ No newline at end of file
!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 json
def file_name(file_dir):
fileList =[]
for root, dirs, files in os.walk(file_dir):
fileList = files
return fileList
fileList = file_name(os.path.abspath('.'))
f = open('filename.txt', 'w')
for fn in fileList:
if fn.split(".")[0] != "creatJsonProfile":
f.write("'" + fn.split(".")[0] + "': 'assets/play/" + fn + "',\n")
f.close()
\ No newline at end of file
'bg-background': 'assets/play/bg-background.png',
'box': 'assets/play/box.png',
'btn-go': 'assets/play/btn-go.png',
'btn-ok': 'assets/play/btn-ok.png',
'card-highlight': 'assets/play/card-highlight.png',
'card': 'assets/play/card.png',
'dish-shaodw': 'assets/play/dish-shaodw.png',
'dish': 'assets/play/dish.png',
'disk': 'assets/play/disk.png',
'light-1': 'assets/play/light-1.png',
'light-2': 'assets/play/light-2.png',
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<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>
<base href="/" />
<style>
html, body{
width: 100%;
height: 100%;
</head>
<body>
<app-root></app-root>
</body>
}
</style>
<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="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>
<!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 */
@import "~ng-zorro-antd/src/ng-zorro-antd.css";
\ No newline at end of file
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