Commit affb7c45 authored by Tt's avatar Tt

init

parent 9f3a2900
# East_L210 游戏引擎 API 文档
## 目录
- [基础工具库 (Unit.ts)](#基础工具库-unitts)
- [精灵类](#精灵类)
- [文本渲染](#文本渲染)
- [形状绘制](#形状绘制)
- [动画控制](#动画控制)
- [工具函数](#工具函数)
- [游戏框架 (Cartoon.ts)](#游戏框架-cartoontss)
- [资源管理](#资源管理)
- [元素创建与管理](#元素创建与管理)
- [坐标系统](#坐标系统)
- [动画控制](#动画控制-1)
- [动画控制器 (CartoonAnimation.ts)](#动画控制器-cartoonanimationts)
- [游戏内容容器 (player-content-wrapper)](#游戏内容容器-player-content-wrapper)
## 基础工具库 (Unit.ts)
`Unit.ts` 提供了游戏开发所需的基础图形、动画和工具函数,是整个引擎的核心组件。
### 精灵类
#### Sprite
基础精灵类,提供位置、绘制和更新功能。
**属性:**
- `x`: 精灵的X坐标
- `y`: 精灵的Y坐标
**方法:**
- `draw(ctx)`: 在画布上绘制精灵
- `update(dt)`: 更新精灵状态
#### MySprite
扩展的精灵类,提供更丰富的功能。
**属性:**
- `x`, `y`: 位置坐标
- `scaleX`, `scaleY`: 缩放比例
- `rotation`: 旋转角度
- `skewX`, `skewY`: 倾斜角度
- `alpha`: 透明度
- `visible`: 可见性
- `width`, `height`: 尺寸
- `anchorX`, `anchorY`: 锚点位置
**方法:**
- `init(img)`: 使用图像初始化精灵
- `setScaleXY(scale)`: 设置统一缩放
- `addChild(child)`: 添加子精灵
- `removeChild(child)`: 移除子精灵
- `removeChildren()`: 移除所有子精灵
- `getBoundingBox()`: 获取包围盒
- `draw(ctx)`: 绘制精灵及其子精灵
- `update(dt)`: 更新精灵及其子精灵
- `show(time, callback)`: 显示精灵(带渐变效果)
#### ColorSpr
带颜色处理功能的精灵类。
**方法:**
- `init(img, color)`: 使用图像和颜色初始化
- `setColor(color)`: 设置精灵颜色
#### GrayscaleSpr
灰度处理精灵类。
**方法:**
- `init(img)`: 使用图像初始化灰度精灵
### 文本渲染
#### Label
文本标签类,支持样式、对齐和特效。
**属性:**
- `text`: 文本内容
- `fontName`: 字体名称
- `fontSize`: 字体大小
- `fontColor`: 字体颜色
- `textAlign`: 文本对齐方式
- `lineHeight`: 行高
- `maxWidth`: 最大宽度(用于自动换行)
**方法:**
- `setShadow(offsetX, offsetY, blur, color)`: 设置文本阴影
- `setOutline(size, color)`: 设置文本描边
- `drawText(ctx)`: 绘制文本
#### BitMapLabel
图像文本类,使用图像渲染文本字符。
**方法:**
- `init(charMap, charWidth, charHeight)`: 初始化字符映射
- `setText(text)`: 设置要显示的文本
#### RichText
富文本类,支持自动换行和行间距控制。
**属性:**
- `text`: 文本内容
- `lineSpacing`: 行间距
**方法:**
- `setText(text)`: 设置文本内容
- `setLineSpacing(spacing)`: 设置行间距
### 形状绘制
#### ShapeRect
矩形绘制类。
**属性:**
- `fillColor`: 填充颜色
- `strokeColor`: 描边颜色
- `lineWidth`: 线宽
**方法:**
- `setSize(width, height)`: 设置矩形尺寸
- `draw(ctx)`: 绘制矩形
#### ShapeRectNew
增强的矩形绘制类,支持圆角。
**属性:**
- `fillColor`: 填充颜色
- `strokeColor`: 描边颜色
- `lineWidth`: 线宽
- `radius`: 圆角半径
**方法:**
- `setSize(width, height)`: 设置矩形尺寸
- `setRadius(radius)`: 设置圆角半径
- `draw(ctx)`: 绘制圆角矩形
#### ShapeCircle
圆形绘制类。
**属性:**
- `fillColor`: 填充颜色
- `strokeColor`: 描边颜色
- `lineWidth`: 线宽
- `radius`: 半径
**方法:**
- `setRadius(radius)`: 设置圆形半径
- `draw(ctx)`: 绘制圆形
### 动画控制
#### MyAnimation
帧动画类,管理和播放序列帧动画。
**属性:**
- `frames`: 帧数组
- `currentFrame`: 当前帧索引
- `loop`: 是否循环播放
- `reverse`: 是否反向播放
- `delay`: 帧延迟时间
**方法:**
- `addFrame(img)`: 添加动画帧
- `addFrameByUrl(url)`: 通过URL添加帧
- `play()`: 开始播放动画
- `stop()`: 停止播放动画
- `replay()`: 重新播放动画
- `reverse()`: 反向播放
- `showAllFrame()`: 显示所有帧
- `hideAllFrame()`: 隐藏所有帧
- `update(dt)`: 更新动画状态
### 工具函数
#### 动画工具
- `tweenChange(item, props, time, callback, easing)`: 属性过渡动画
- `rotateItem(item, angle, time, callback, easing)`: 旋转动画
- `scaleItem(item, scale, time, callback, easing)`: 缩放动画
- `moveItem(item, x, y, time, callback, easing)`: 移动动画
- `alphaItem(item, alpha, time, callback, easing)`: 透明度动画
- `hideItem(item, time, callback)`: 隐藏元素动画
- `showItem(item, time, callback)`: 显示元素动画
- `endShow(item, time, callback)`: 弹性显示动画
- `jelly(item, time)`: 果冻弹跳效果
- `shake(item, time, callback, rate)`: 抖动效果
- `circleMove(item, x0, y0, time, addR, xPer, yPer, callback, easing)`: 圆周运动
#### 数学工具
- `randomSortByArr(arr)`: 数组随机排序
- `radianToAngle(radian)`: 弧度转角度
- `angleToRadian(angle)`: 角度转弧度
- `getPosByAngle(angle, len)`: 根据角度和长度获取坐标
- `getAngleByPos(x, y, cx, cy)`: 获取点相对于中心点的角度
- `getPosDistance(sx, sy, ex, ey)`: 计算两点间距离
- `removeItemFromArr(arr, item)`: 从数组中移除项
- `getMinScale(item, maxLen)`: 计算等比缩放比例
#### 特效工具
- `showPopParticle(img, pos, parent)`: 创建烟花爆炸效果
- `showBlingBling(starImg, rectArea, parent, mapScale, num, disTime, showTime)`: 创建闪烁星星效果
- `delayCall(callback, second)`: 延迟调用函数
## 游戏框架 (Cartoon.ts)
`Cartoon.ts` 提供了游戏资源管理、元素创建和坐标系统等高级功能。
### 资源管理
#### 音频管理
**属性:**
- `audio`: 存储音频对象的Map
- `audioObj`: 音频URL对象
**方法:**
- `addAudio(key, url)`: 添加音频资源
- `playAudio(key, now, callback)`: 播放音频
- `stopAudio()`: 停止当前播放的音频
- `stopAllAudio()`: 停止所有正在播放的音频
#### 图像管理
**属性:**
- `images`: 存储图像对象的Map
- `imagesOriginSize`: 存储图像原始尺寸的Map
- `imageObj`: 图像URL对象
**方法:**
- `addImage(key, url)`: 添加图像资源
- `preloadImage(url)`: 预加载单个图像
- `preloadAudio(url)`: 预加载单个音频
- `loadResources()`: 加载所有资源
### 元素创建与管理
**属性:**
- `cartoonElementsBuffer`: 缓存的元素对象
**方法:**
- `createCartoonElement(key, type, width, height, initX, initY)`: 创建并缓存元素
- `createElement(type, initX, initY)`: 创建临时元素
- `createLabel(config, initX, initY)`: 创建文本标签
- `getCartoonElementRef(key)`: 获取元素引用
- `getCartoonElement(key)`: 获取元素对象
### 坐标系统
**属性:**
- `mapScale`: 系统缩放比例
- `stageWidth`, `stageHeight`: 舞台尺寸
- `clientWidth`, `clientHeight`: 客户端尺寸
- `originX`, `originY`: 全局坐标原点
- `relativeOriginX`, `relativeOriginY`: 相对坐标原点
**方法:**
- `setOrigin(x, y)`: 设置全局坐标原点
- `getOrigin()`: 获取全局坐标原点
- `setRelativeOrigin(x, y)`: 设置相对坐标原点
- `getRelativeOrigin()`: 获取相对坐标原点
- `setCartoonElementPosition(key, posi)`: 设置元素位置
- `setCartoonElementPositionX(key, x)`: 设置元素X坐标
- `setCartoonElementPositionY(key, y)`: 设置元素Y坐标
- `setCartoonElementRelativePositionX(key, x)`: 设置元素相对X坐标
- `setCartoonElementRelativePositionY(key, y)`: 设置元素相对Y坐标
- `getCartoonElementPosition(key)`: 获取元素位置
- `getCartoonElementRelativePosition(key)`: 获取元素相对位置
### 动画控制
**属性:**
- `animation`: 全局动画控制器
## 动画控制器 (CartoonAnimation.ts)
`CartoonAnimation.ts` 提供了单个元素的动画控制功能。
**属性:**
- `animations`: 存储注册的动画函数
- `currentRef`: 当前操作的元素引用
**方法:**
- `add(key, func)`: 添加自定义动画
- `move(ele, distPosition, runTime, callback)`: 移动元素
- `scaleChange(ele, distPosition, runTime, callback)`: 改变元素缩放
- `run(key)`: 运行指定名称的动画
- `overCard(callback)`: 卡片翻转动画
## 游戏内容容器 (player-content-wrapper)
`player-content-wrapper.component.ts` 是一个Angular组件,用于包装和适配游戏内容,确保游戏在不同屏幕尺寸下保持正确的宽高比。
### 组件结构
**TypeScript (player-content-wrapper.component.ts):**
**属性:**
- `ratio`: 宽高比例,默认为'20-9'
- `_w`, `_h`: 容器宽高,根据屏幕方向自动调整
- `wrapperEl`: 对容器DOM元素的引用
**方法:**
- 实现了Angular的生命周期钩子:`ngOnInit`, `ngOnChanges`, `ngOnDestroy`, `ngAfterViewInit`
**HTML模板 (player-content-wrapper.component.html):**
```html
<div class="cmp-player-content-wrapper" #wrapperEl>
<div class="cmp-cnt-box">
<img [src]="'assets/'+ratio+'.png'" alt="">
<div class="cmp-cnt-main">
<ng-content></ng-content>
</div>
</div>
</div>
```
**样式 (player-content-wrapper.component.scss):**
组件使用了灵活的布局方式,确保内容在保持宽高比的同时能够适应不同屏幕尺寸:
- 使用相对定位和绝对定位实现内容叠加
- 支持CSS自定义属性`--aspect-ratio`进行宽高比控制
- 使用Flexbox布局管理内部内容
## 使用示例
### 基础精灵创建与动画
```typescript
// 创建游戏框架实例
const cartoon = new Cartoon();
// 添加资源
cartoon.addImage('player', 'assets/player.png');
cartoon.addAudio('bgm', 'assets/bgm.mp3');
// 加载资源
cartoon.loadResources().then(() => {
// 创建精灵
const player = cartoon.createCartoonElement('player', 'MySprite', 100, 100, 200, 300);
// 初始化精灵图像
player.ref.init(cartoon.images.get('player'));
// 播放背景音乐
cartoon.playAudio('bgm');
// 创建移动动画
player.animation.move(player.ref, {x: 400, y: 500}, 2, () => {
console.log('移动完成');
});
});
```
### 文本与形状绘制
```typescript
// 创建文本标签
const label = cartoon.createCartoonElement('title', 'Label', 200, 50, 100, 100);
label.ref.text = '游戏标题';
label.ref.fontSize = 30;
label.ref.fontColor = '#FFFFFF';
label.ref.setShadow(2, 2, 2, '#000000');
// 创建圆角矩形背景
const bg = cartoon.createCartoonElement('bg', 'ShapeRectNew', 300, 200, 50, 50);
bg.ref.fillColor = '#3366CC';
bg.ref.setRadius(10);
```
### 自定义动画
```typescript
// 创建自定义动画
player.animation.add('jump', () => {
// 跳跃动画:先上升后下降
const baseY = player.ref.y;
// 上升阶段
moveItem(player.ref, player.ref.x, baseY - 100, 0.5, () => {
// 下降阶段
moveItem(player.ref, player.ref.x, baseY, 0.3, () => {
// 添加弹性效果
jelly(player.ref, 0.5);
});
});
});
// 运行动画
player.animation.run('jump');
```
### 坐标系统使用
```typescript
// 设置全局坐标原点(屏幕中心)
cartoon.setOrigin(window.innerWidth / 2, window.innerHeight / 2);
// 创建相对于原点的元素
const star = cartoon.createCartoonElement('star', 'MySprite', 50, 50, 0, 0);
star.ref.init(cartoon.images.get('star'));
// 使用圆周运动
circleMove(star.ref, 0, 0, 3, 360, 1, 1, () => {
console.log('圆周运动完成');
});
```
### 特效使用
```typescript
// 创建爆炸效果
showPopParticle(cartoon.images.get('particle'), {x: 200, y: 300}, parentContainer);
// 创建闪烁星星效果
showBlingBling(cartoon.images.get('star'), {width: 400, height: 300}, parentContainer);
// 添加抖动效果
shake(player.ref, 0.5, () => {
console.log('抖动完成');
});
```
### 在Angular应用中集成
以下是在Angular组件中集成游戏引擎的示例:
**游戏组件TypeScript:**
```typescript
import { Component, ElementRef, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { Cartoon } from '../../play/Cartoon';
import { MySprite, moveItem } from '../../play/Unit';
@Component({
selector: 'app-game',
templateUrl: './game.component.html',
styleUrls: ['./game.component.scss']
})
export class GameComponent implements OnInit, AfterViewInit {
@ViewChild('gameCanvas', { static: true }) canvasRef: ElementRef;
private cartoon: Cartoon;
private canvas: HTMLCanvasElement;
private ctx: CanvasRenderingContext2D;
private animationFrameId: number;
constructor() { }
ngOnInit() {
// 初始化游戏框架
this.cartoon = new Cartoon();
// 添加资源
this.cartoon.addImage('player', 'assets/images/player.png');
this.cartoon.addAudio('bgm', 'assets/audio/bgm.mp3');
}
ngAfterViewInit() {
// 获取画布和上下文
this.canvas = this.canvasRef.nativeElement;
this.ctx = this.canvas.getContext('2d');
// 设置画布尺寸
this.resizeCanvas();
window.addEventListener('resize', () => this.resizeCanvas());
// 加载资源并初始化游戏
this.cartoon.loadResources().then(() => {
this.initGame();
this.startGameLoop();
});
}
private resizeCanvas() {
// 设置画布尺寸为容器尺寸
this.canvas.width = this.canvas.parentElement.clientWidth;
this.canvas.height = this.canvas.parentElement.clientHeight;
// 更新游戏框架的舞台尺寸
this.cartoon.stageWidth = this.canvas.width;
this.cartoon.stageHeight = this.canvas.height;
// 设置坐标原点为画布中心
this.cartoon.setOrigin(this.canvas.width / 2, this.canvas.height / 2);
}
private initGame() {
// 创建游戏元素
const player = this.cartoon.createCartoonElement('player', 'MySprite', 100, 100, 0, 0);
player.ref.init(this.cartoon.images.get('player'));
// 播放背景音乐
this.cartoon.playAudio('bgm');
}
private startGameLoop() {
// 上一帧时间戳
let lastTime = 0;
// 游戏循环函数
const animate = (timestamp) => {
// 计算时间差(秒)
const deltaTime = (timestamp - lastTime) / 1000;
lastTime = timestamp;
// 清除画布
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// 保存上下文状态
this.ctx.save();
// 将坐标系移动到画布中心
this.ctx.translate(this.cartoon.originX, this.cartoon.originY);
// 遍历所有游戏元素并绘制
for (const key in this.cartoon.cartoonElementsBuffer) {
const element = this.cartoon.cartoonElementsBuffer[key];
element.ref.update(deltaTime);
element.ref.draw(this.ctx);
}
// 恢复上下文状态
this.ctx.restore();
// 请求下一帧
this.animationFrameId = requestAnimationFrame(animate);
};
// 开始游戏循环
this.animationFrameId = requestAnimationFrame(animate);
}
ngOnDestroy() {
// 停止游戏循环
if (this.animationFrameId) {
cancelAnimationFrame(this.animationFrameId);
}
// 停止所有音频
this.cartoon.stopAllAudio();
}
}
```
**游戏组件HTML:**
```html
<app-player-content-wrapper [ratio]="'16-9'">
<div class="game-container">
<canvas #gameCanvas></canvas>
</div>
</app-player-content-wrapper>
```
**游戏组件SCSS:**
```scss
.game-container {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
canvas {
display: block;
width: 100%;
height: 100%;
}
}
```
**在AppModule中导入:**
```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { GameComponent } from './game/game.component';
import { PlayerContentWrapperComponent } from './common/player-content-wrapper/player-content-wrapper.component';
@NgModule({
declarations: [
AppComponent,
GameComponent,
PlayerContentWrapperComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
\ No newline at end of file
......@@ -353,64 +353,4 @@ npm start
点击“模板管理” 菜单,找到对应的模板卡片,点击“发布”按钮,在弹出的对话框中选中压缩包,然后点击“确定”,上传完成后,则发布就成功了
## 常见问题汇总
### 静态资源引用路径写法
css文件里面要带 .. , eg:
```
background-image: url("../../assets/playground-house/bg.jpg");
```
其他的文件(html、ts、resources.js)里路径要开头不带斜杠, eg:
```
src="assets/guess-read/btn.png"
```
### no such file or directory,
出现类似如:
```
Error: ENOENT: no such file or directory, open 'C:/publish/resources/xxxx/v1/index.html'
```
这样的代码时, 请确认新建模板的时候表单填写的“配置页面URL”与“展示页面URL” 填写的路径是否正确
### 已经发布的模板,制作课件时看不到
如果模板已经确认发布成功了,制作课件的时候却看不到这个模板,请编辑模板,查看模板类型是否选择为“课中模板”
### 有些模板上传图片或视频时,存在偶尔上传不上去的问题
此问题是因为有些异步的情况下 uploadUrl 获取不到导致的
在 constructor 或者 ngOnInit 方法里,一直轮询,直到获取到 uploadUrl
```
this.uploadUrl = (<any> window).courseware.uploadUrl();
this.uploadData = (<any> window).courseware.uploadData();
const fun = () => {
setTimeout(() => {
this.uploadUrl = (<any> window).courseware.uploadUrl();
this.uploadData = (<any> window).courseware.uploadData();
if(!this.uploadUrl){
fun();
}
}, 1000);
}
if(!this.uploadUrl){
fun();
}
```
### 模板编译CI不通过,报类似如下错误
```
ERROR in ./src/styles.scss Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js): ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): Error: Node Sass version 5.0.0 is incompatible with ^4.0.0. at getSassImplementation
```
此情况属于老的模板遗留问题,需要在package.json里面锁一下node-sass的版本
```
"node-sass": "4.0.0"
```
\ No newline at end of file
Angular项目开发AI协作提示词模板
技术栈声明
1. 核心框架:Angular
2. 框架组件: 均在项目根目录下的 src/app/common 目录下
3. 需要操作的代码为: src/app/form/form.component.html 和 src/app/form/form.component.ts
需求描述框架
[模块名称]
- 功能目标:使用Angular开发一个表单组件,包含文本输入框和音频上传功能。
- 技术约束:优先使用框架组件,避免使用外部的第三方组件
- 预期输出:代码尽可能简单,避免使用复杂的逻辑
交互规范
当回答技术问题时:
1. 脚本代码必须给出TypeScript实现方案
......@@ -29,7 +29,7 @@
}
],
"styles": [
"./node_modules/ng-zorro-antd/ng-zorro-antd.min.css",
"node_modules/ng-zorro-antd/ng-zorro-antd.min.css",
"src/styles.css"
],
"scripts": []
......@@ -94,7 +94,7 @@
"src/assets"
],
"styles": [
"./node_modules/ng-zorro-antd/ng-zorro-antd.min.css",
"node_modules/ng-zorro-antd/ng-zorro-antd.min.css",
"src/styles.css"
],
"scripts": []
......@@ -128,5 +128,8 @@
}
}
},
"defaultProject": "ng-template-generator"
"defaultProject": "ng-template-generator",
"cli": {
"analytics": "0bdaa560-1d2a-46f5-b14c-1f80decb439e"
}
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -32,7 +32,7 @@
"spark-md5": "^3.0.0",
"tslib": "^1.10.0",
"zone.js": "~0.10.2",
"node-sass": "4.0.0"
"node-sass": "^4.0.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.900.3",
......
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 { AppComponent } from './app.component';
import { FormComponent } from './form/form.component';
import { PlayComponent } from "./play/play.component";
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 {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);
import { FontAwesomeModule, FaIconLibrary } from '@fortawesome/angular-fontawesome';
import { fas } from '@fortawesome/free-solid-svg-icons';
import { far } from '@fortawesome/free-regular-svg-icons';
registerLocaleData(zh);
@NgModule({
declarations: [
......@@ -40,20 +45,18 @@ registerLocaleData(zh);
TimePipe,
UploadVideoComponent,
CustomHotZoneComponent,
PlayerContentWrapperComponent
],
imports: [
BrowserModule,
NgZorroAntdModule,
FormsModule,
HttpClientModule,
BrowserAnimationsModule,
BrowserModule,
NgZorroAntdModule,
FontAwesomeModule
],
providers: [
{provide: ErrorHandler, useClass: MyErrorHandler},
/** 配置 ng-zorro-antd 国际化(文案 及 日期) **/
providers : [
{ provide: NZ_I18N, useValue: zh_CN }
],
bootstrap: [AppComponent]
......
<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-icon name="close"></fa-icon>
</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;
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();
......@@ -55,13 +54,7 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
constructor( private nzMessageService: NzMessageService ) {
this.uploadUrl = (<any> window).courseware.uploadUrl();
this.uploadData = (<any> window).courseware.uploadData();
window['air'].getUploadCallback = (url, data) => {
this.uploadUrl = url;
this.uploadData = data;
};
}
init() {
......@@ -151,7 +144,6 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
onBtnSwitchType() {
}
onBtnClearAudio() {
this.audioUrl = null;
this.audioRemoved.emit();
}
......@@ -194,7 +186,6 @@ export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
return true;
}
beforeUpload = (file: File) => {
this.audioUrl = null;
if (!this.checkSelectFile(file)) {
return false;
......@@ -205,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;
......
import TWEEN from '@tweenjs/tween.js';
interface AirWindow extends Window {
air: any;
curCtx: any;
}
declare let window: AirWindow;
class Sprite {
x = 0;
......@@ -17,13 +12,9 @@ class Sprite {
angle = 0;
ctx;
constructor(ctx = null) {
if (!ctx) {
this.ctx = window.curCtx;
} else {
constructor(ctx) {
this.ctx = ctx;
}
}
update($event) {
this.draw();
}
......@@ -39,45 +30,25 @@ class Sprite {
export class MySprite extends Sprite {
_width = 0;
_height = 0;
width = 0;
height = 0;
_anchorX = 0;
_anchorY = 0;
_offX = 0;
_offY = 0;
scaleX = 1;
scaleY = 1;
_alpha = 1;
alpha = 1;
rotation = 0;
visible = true;
skewX = 0;
skewY = 0;
_shadowFlag = false;
_shadowColor;
_shadowOffsetX = 0;
_shadowOffsetY = 0;
_shadowBlur = 5;
_radius = 0;
children = [this];
childDepandVisible = true;
childDepandAlpha = false;
img;
_z = 0;
_showRect;
_bitmapFlag = false;
_offCanvas;
_offCtx;
init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) {
init(imgObj = null, anchorX:number = 0.5, anchorY:number = 0.5) {
if (imgObj) {
......@@ -85,8 +56,6 @@ export class MySprite extends Sprite {
this.width = this.img.width;
this.height = this.img.height;
}
this.anchorX = anchorX;
......@@ -94,35 +63,11 @@ export class MySprite extends Sprite {
}
setShowRect(rect) {
this._showRect = rect;
}
setShadow(offX, offY, blur, color = 'rgba(0, 0, 0, 0.3)') {
this._shadowFlag = true;
this._shadowColor = color;
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
this._shadowBlur = blur;
}
setRadius(r) {
this._radius = r;
}
update($event = null) {
if (!this.visible && this.childDepandVisible) {
return;
}
if (this.visible) {
this.draw();
}
}
draw() {
......@@ -133,8 +78,6 @@ export class MySprite extends Sprite {
this.updateChildren();
this.ctx.restore();
}
drawInit() {
......@@ -147,87 +90,38 @@ export class MySprite extends Sprite {
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) {
if (this._showRect) {
const rect = this._showRect;
this.ctx.drawImage(this.img, rect.x, rect.y, rect.width, rect.height, this._offX, this._offY + rect.y, this.width, rect.height);
} else {
this.ctx.drawImage(this.img, this._offX, this._offY);
}
}
}
updateChildren() {
if (this.children.length <= 0) { return; }
for (const child of this.children) {
if (child === this) {
if (this.visible) {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i] === this) {
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;
});
......@@ -244,11 +138,6 @@ 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);
......@@ -257,55 +146,6 @@ export class MySprite extends Sprite {
}
}
removeChildren() {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i]) {
if (this.children[i] !== this) {
this.children.splice(i, 1);
i --;
}
}
}
}
_changeChildAlpha(alpha) {
for (const child of this.children) {
if (child !== this) {
child.alpha = alpha;
}
}
}
set btimapFlag(v) {
this._bitmapFlag = v;
}
get btimapFlag() {
return this._bitmapFlag;
}
set alpha(v) {
this._alpha = v;
if (this.childDepandAlpha) {
this._changeChildAlpha(v);
}
}
get alpha() {
return this._alpha;
}
set width(v) {
this._width = v;
this.refreshAnchorOff();
}
get width() {
return this._width;
}
set height(v) {
this._height = v;
this.refreshAnchorOff();
}
get height() {
return this._height;
}
set anchorX(value) {
this._anchorX = value;
this.refreshAnchorOff();
......@@ -321,8 +161,8 @@ export class MySprite extends Sprite {
return this._anchorY;
}
refreshAnchorOff() {
this._offX = -this._width * this.anchorX;
this._offY = -this._height * this.anchorY;
this._offX = -this.width * this.anchorX;
this._offY = -this.height * this.anchorY;
}
setScaleXY(value) {
......@@ -331,42 +171,10 @@ export class MySprite extends Sprite {
getBoundingBox() {
const getParentData = (item) => {
let px = item.x;
let py = item.y;
let sx = item.scaleX;
let sy = item.scaleY;
const parent = item.parent;
if (parent) {
const obj = getParentData(parent);
const _x = obj.px;
const _y = obj.py;
const _sx = obj.sx;
const _sy = obj.sy;
px = _x + item.x * _sx;
py = _y + item.y * _sy;
sx *= _sx;
sy *= _sy;
}
return {px, py, sx, sy};
};
const data = getParentData(this);
const x = data.px + this._offX * Math.abs(data.sx);
const y = data.py + this._offY * Math.abs(data.sy);
const width = this.width * Math.abs(data.sx);
const height = this.height * Math.abs(data.sy);
const x = this.x + this._offX * this.scaleX;
const y = this.y + this._offY * this.scaleY;
const width = this.width * this.scaleX;
const height = this.height * this.scaleY;
return {x, y, width, height};
}
......@@ -374,1640 +182,220 @@ export class MySprite extends Sprite {
}
export class RoundSprite extends MySprite {
_newCtx;
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;
const canvas = window['curCanvas'];
const w = canvas.nativeElement.width;
const h = canvas.nativeElement.height;
this._offCanvas = document.createElement('canvas');
this._offCanvas.width = w;
this._offCanvas.height = h;
this._offCtx = this._offCanvas.getContext('2d');
export class Item extends MySprite {
// this._newCtx = this.ctx;
// this.ctx = this._offCtx;
baseX;
}
move(targetY, callBack) {
const self = this;
const tween = new TWEEN.Tween(this)
.to({ y: targetY }, 2500)
.easing(TWEEN.Easing.Quintic.Out)
.onComplete(function() {
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;
self.hide(callBack);
// if (callBack) {
// callBack();
// }
})
.start();
if (this._radius) {
const r = this._radius;
const w = this.width;
const h = this.height;
const x = -this._offX;
const y = -this._offY;
this._offCtx.lineTo(x - w / 2, y + h / 2); // 创建水平线
this._offCtx.arcTo(x - w / 2, y - h / 2, x - w / 2 + r, y - h / 2, r);
this._offCtx.arcTo(x + w / 2, y - h / 2, x + w / 2, y - h / 2 + r, r);
this._offCtx.arcTo(x + w / 2, y + h / 2, x + w / 2 - r, y + h / 2, r);
this._offCtx.arcTo(x - w / 2, y + h / 2, x - w / 2, y + h / 2 - r, r);
this._offCtx.clip();
}
show(callBack = null) {
if (this.img) {
this._offCtx.drawImage(this.img, 0, 0);
this.ctx.drawImage(this._offCanvas,this._offX, this._offX);
const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(function() {
if (callBack) {
callBack();
}
})
.start(); // Start the tween immediately.
}
}
export class ColorSpr extends MySprite {
hide(callBack = null) {
r = 0;
g = 0;
b = 0;
createGSCanvas() {
if (!this.img) {
return;
const tween = new TWEEN.Tween(this)
.to({ alpha: 0 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(function() {
if (callBack) {
callBack();
}
const rect = this.getBoundingBox();
if (rect.width <= 1 || rect.height <= 1) {
return;
})
.start(); // Start the tween immediately.
}
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for ( let i = 0; i < c.height; i++) {
for ( let j = 0; j < c.width; j++) {
const x = (i * 4) * c.width + ( j * 4 );
const r = c.data[x];
const g = c.data[x + 1];
const b = c.data[x + 2];
c.data[x] = this.r;
c.data[x + 1] = this.g;
c.data[x + 2] = this.b;
shake(id) {
// c.data[x] = c.data[x + 1] = c.data[x + 2] = (r + g + b) / 3 ;
// // c.data[x + 3] = 255;
}
}
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
}
drawSelf() {
super.drawSelf();
this.createGSCanvas();
if (!this.baseX) {
this.baseX = this.x;
}
}
const baseX = this.baseX;
const baseTime = 50;
const sequence = [
{target: {x: baseX + 40 * id}, time: baseTime - 25},
{target: {x: baseX - 20 * id}, time: baseTime},
{target: {x: baseX + 10 * id}, time: baseTime},
{target: {x: baseX - 5 * id}, time: baseTime},
{target: {x: baseX + 2 * id}, time: baseTime},
{target: {x: baseX - 1 * id}, time: baseTime},
{target: {x: baseX}, time: baseTime},
];
export class GrayscaleSpr extends MySprite {
grayScale = 120;
const self = this;
createGSCanvas() {
function runSequence() {
if (!this.img) {
return;
if (self['shakeTween']) {
self['shakeTween'].stop();
}
const tween = new TWEEN.Tween(self);
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 );
const r = c.data[x];
const g = c.data[x + 1];
const b = c.data[x + 2];
// const a = c.data[x + 3];
c.data[x] = c.data[x + 1] = c.data[x + 2] = this.grayScale; // (r + g + b) / 3;
// c.data[x + 3] = 255;
}
if (sequence.length > 0) {
const action = sequence.shift();
tween.to(action['target'], action['time']);
tween.onComplete( () => {
runSequence();
});
tween.start();
self['shakeTween'] = tween;
}
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
}
runSequence();
drawSelf() {
super.drawSelf();
this.createGSCanvas();
}
}
drop(targetY, callBack = null) {
export class BitMapLabel extends MySprite {
const self = this;
const time = Math.abs(targetY - this.y) * 2.4;
labelArr;
baseUrl;
this.alpha = 1;
setText(data, text) {
this.labelArr = [];
const labelArr = [];
const tmpArr = text.split('');
let totalW = 0;
let h = 0;
for (const tmp of tmpArr) {
const label = new MySprite(this.ctx);
label.init(data[tmp], 0);
this.addChild(label);
labelArr.push(label);
const tween = new TWEEN.Tween(this)
.to({ y: targetY }, time)
.easing(TWEEN.Easing.Cubic.In)
.onComplete(function() {
totalW += label.width;
h = label.height;
// self.hideItem(callBack);
if (callBack) {
callBack();
}
})
.start();
this.width = totalW;
this.height = h;
let offX = -totalW / 2;
for (const label of labelArr) {
label.x = offX;
offX += label.width;
}
this.labelArr = labelArr;
}
}
export class EndSpr extends MySprite {
show(s) {
export class Label extends MySprite {
private _text: string;
// fontSize:String = '40px';
fontName = 'Verdana';
textAlign = 'left';
fontSize = 40;
fontColor = '#000000';
fontWeight = 900;
_maxWidth;
outline = 0;
outlineColor = '#ffffff';
// _shadowFlag = false;
// _shadowColor;
// _shadowOffsetX;
// _shadowOffsetY;
// _shadowBlur;
_outlineFlag = false;
_outLineWidth;
_outLineColor;
constructor(ctx = null) {
super(ctx);
this.init();
}
get text(): string {
return this._text;
}
set text(value: string) {
this._text = value;
this.refreshSize();
}
refreshSize() {
this.ctx.save();
this.ctx.font = `${this.fontSize * this.scaleX}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
this._width = this.ctx.measureText(this.text).width;
this._height = this.fontSize;
this.refreshAnchorOff();
this.ctx.restore();
}
setMaxSize(w) {
this._maxWidth = w;
this.refreshSize();
if (this.width >= w) {
this.scaleX *= w / this.width;
this.scaleY *= w / this.width;
}
}
show(callBack = null) {
this.visible = true;
if (this.alpha >= 1) {
return;
}
this.scaleX = this.scaleY = 0;
this.alpha = 0;
const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
.to({ alpha: 1, scaleX: s, scaleY: s }, 800)
.easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
.onComplete(function() {
})
.start(); // Start the tween immediately.
}
setOutline(width = 5, color = '#ffffff') {
this._outlineFlag = true;
this._outLineWidth = width;
this._outLineColor = color;
}
drawText() {
if (!this.text) { return; }
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor;
this.ctx.strokeText(this.text, 0, 0);
}
}
this.ctx.fillStyle = this.fontColor;
if (this.outline > 0) {
this.ctx.lineWidth = this.outline;
this.ctx.strokeStyle = this.outlineColor;
this.ctx.strokeText(this.text, 0, 0);
}
this.ctx.fillText(this.text, 0, 0);
export class ShapeRect extends MySprite {
fillColor = '#FF0000';
setSize(w, h) {
this.width = w;
this.height = h;
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class RichTextOld extends Label {
textArr = [];
fontSize = 40;
setText(text: string, words) {
let newText = text;
for (const word of words) {
const re = new RegExp(word, 'g');
newText = newText.replace( re, `#${word}#`);
// newText = newText.replace(word, `#${word}#`);
}
this.textArr = newText.split('#');
this.text = newText;
// this.setSize();
}
refreshSize() {
this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
let curX = 0;
for (const text of this.textArr) {
const w = this.ctx.measureText(text).width;
curX += w;
}
this.width = curX;
this.height = this.fontSize;
this.refreshAnchorOff();
this.ctx.restore();
}
show(callBack = null) {
// console.log(' in show ');
this.visible = true;
// this.alpha = 0;
const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
})
.start(); // Start the tween immediately.
}
drawText() {
// console.log('in drawText', this.text);
if (!this.text) { return; }
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = 900;
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = '#ffffff';
// this.ctx.strokeText(this.text, 0, 0);
this.ctx.fillStyle = '#000000';
// this.ctx.fillText(this.text, 0, 0);
let curX = 0;
for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width;
if ((i + 1) % 2 === 0) {
this.ctx.fillStyle = '#c8171e';
} else {
this.ctx.fillStyle = '#000000';
}
this.ctx.fillText(this.textArr[i], curX, 0);
curX += w;
}
}
}
export class RichText extends Label {
disH = 30;
constructor(ctx?: any) {
super(ctx);
// this.dataArr = dataArr;
}
drawText() {
if (!this.text) {
return;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
this.ctx.fillStyle = this.fontColor;
const selfW = this.width * this.scaleX;
const chr = this.text.split(' ');
let temp = '';
const row = [];
const w = selfW - 80;
const disH = (this.fontSize + this.disH) * this.scaleY;
for (const c of chr) {
if (this.ctx.measureText(temp).width < w && this.ctx.measureText(temp + (c)).width <= w) {
temp += ' ' + c;
} else {
row.push(temp);
temp = ' ' + c;
}
}
row.push(temp);
const x = 0;
const y = -row.length * disH / 2;
// for (let b = 0 ; b < row.length; b++) {
// this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
// }
if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor;
for (let b = 0 ; b < row.length; b++) {
this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
}
// this.ctx.strokeText(this.text, 0, 0);
}
// this.ctx.fillStyle = '#ff7600';
for (let b = 0 ; b < row.length; b++) {
this.ctx.fillText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
}
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class LineRect extends MySprite {
lineColor = '#ffffff';
lineWidth = 10;
setSize(w, h) {
this.width = w;
this.height = h;
}
drawLine() {
this.ctx.beginPath();
this.ctx.moveTo(this._offX, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY + this.height);
this.ctx.lineTo(this._offX, this._offY + this.height);
this.ctx.closePath();
this.ctx.lineWidth = this.lineWidth;
// this.ctx.fillStyle = "rgb(2,33,42)"; //指定填充颜色
// this.ctx.fill(); //对多边形进行填充
this.ctx.strokeStyle = this.lineColor; // "#ffffff";
this.ctx.stroke();
}
drawSelf() {
super.drawSelf();
this.drawLine();
}
}
export class ShapeRect extends MySprite {
fillColor = '#FF0000';
setSize(w, h) {
this.width = w;
this.height = h;
// console.log('w:', w);
// console.log('h:', h);
}
drawShape() {
drawShape() {
this.ctx.fillStyle = this.fillColor;
this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class Line extends MySprite {
lineWidth = 5;
lineColor = '#000000';
_pointArr = [];
roundFlag = true;
_pointS = 1;
imgObj;
bitMap;
_offCtx;
_offCanvas;
lastPointIndex = 0;
init() {
const canvas = window['curCanvas'];
const w = canvas.nativeElement.width;
const h = canvas.nativeElement.height;
console.log('w: ', w);
console.log('h: ', h);
this._offCanvas = document.createElement('canvas');
this._offCanvas.width = w;
this._offCanvas.height = h;
// this._offCanvas = _offCanvas;
// this._offCtx = this._offCanvas.getContext('2d');
// this._offCanvas = new OffscreenCanvas(w, h);
this._offCtx = this._offCanvas.getContext('2d');
}
addPoint(x, y) {
this._pointArr.push([x, y]);
if (this._pointArr.length < 2) {
return;
}
//
// const lastP = this._pointArr[this._pointArr.length - 1];
//
//
// const context = this._offCtx;
// context.moveTo (lastP[0], lastP[1]); // 设置起点状态
// context.lineTo (x, y); // 设置末端状态
//
// context.lineWidth = this.lineWidth; //设置线宽状态
// context.strokeStyle = this.lineColor;
// context.stroke();
//
//
// this.bitMap = this._offCanvas.transferToImageBitmap();
// const tmpLine = new MySprite(this._offCtx);
// tmpLine.init(this.imgObj);
// tmpLine.anchorY = 1;
// tmpLine.anchorX = 0.5;
// tmpLine.x = lastP[0];
// tmpLine.y = lastP[1];
//
// const disH = getPosDistance(lastP[0], lastP[1], x, y);
// tmpLine.scaleX = this.lineWidth / tmpLine.width;
// tmpLine.scaleY = disH / tmpLine.height * 1.1;
//
// const angle = getAngleByPos(lastP[0], lastP[1], x, y);
// tmpLine.rotation = angle;
//
// this.addChild(tmpLine);
}
setPointArr(arr, imgObj) {
this.removeChildren();
if (arr.length < 2) {
return;
}
let p1 = arr[0];
let p2;
for (let i = 1; i < arr.length; i++) {
p2 = arr[i];
const tmpLine = new MySprite();
tmpLine.init(imgObj);
tmpLine.anchorY = 1;
tmpLine.anchorX = 0.5;
tmpLine.x = p1[0];
tmpLine.y = p1[1];
const disH = getPosDistance(p1[0], p1[1], p2[0], p2[1]);
tmpLine.scaleX = this.lineWidth / tmpLine.width;
tmpLine.scaleY = disH / tmpLine.height * 1.1;
const angle = getAngleByPos(p1[0], p1[1], p2[0], p2[1]);
tmpLine.rotation = angle;
this.addChild(tmpLine);
p1 = p2;
}
}
drawLine() {
if (this._pointArr.length < 2) {
return;
}
const curMaxPointIndex = this._pointArr.length - 1;
if (curMaxPointIndex > this.lastPointIndex) {
const arr = this._pointArr;
const context = this._offCtx;
context.moveTo (arr[this.lastPointIndex][0] * this._pointS, arr[this.lastPointIndex][1] * this._pointS); // 设置起点状态
for (let i = this.lastPointIndex + 1; i < arr.length; i++) {
context.lineTo (arr[i][0] * this._pointS, arr[i][1] * this._pointS); // 设置末端状态
}
if (this.roundFlag) {
context.lineCap = "round";
}
context.lineWidth = this.lineWidth; //设置线宽状态
context.strokeStyle = this.lineColor;
context.stroke();
this.lastPointIndex = curMaxPointIndex;
// this.bitMap = this._offCanvas.transferToImageBitmap();
}
// this.ctx.drawImage(this.bitMap, this._offX, this._offY);
this.ctx.drawImage(this._offCanvas, this._offX, this._offY);
}
drawSelf() {
super.drawSelf();
this.drawLine();
// if (this.img) {
// this.ctx.drawImage(this._offCanvas, 0, 0, this.width, this.height);
// }
// if (this.bitMap) {
// this.bitMap = this._offCanvas.transferToImageBitmap();
// this.ctx.drawImage(this.bitMap, 0, 0, this.width, this.height);
// }
}
}
export class ShapeCircle extends MySprite {
fillColor = '#FF0000';
radius = 0;
setRadius(r) {
this.anchorX = this.anchorY = 0.5;
this.radius = r;
this.width = r * 2;
this.height = r * 2;
}
drawShape() {
this.ctx.beginPath();
this.ctx.fillStyle = this.fillColor;
this.ctx.arc(0, 0, this.radius, 0, angleToRadian(360));
this.ctx.fill();
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class ShapeRectNew extends MySprite {
radius = 0;
fillColor = '#ffffff';
strokeColor = '#000000';
fill = true;
stroke = false;
lineWidth = 1;
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
drawShape() {
const ctx = this.ctx;
const width = this.width;
const height = this.height;
const radius = this.radius;
ctx.save();
ctx.beginPath(0);
// 从右下角顺时针绘制,弧度从0到1/2PI
ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
// 矩形下边线
ctx.lineTo(radius, height);
// 左下角圆弧,弧度从1/2PI到PI
ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
// 矩形左边线
ctx.lineTo(0, radius);
// 左上角圆弧,弧度从PI到3/2PI
ctx.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
// 上边线
ctx.lineTo(width - radius, 0);
// 右上角圆弧
ctx.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
// 右边线
ctx.lineTo(width, height - radius);
ctx.closePath();
if (this.fill) {
ctx.fillStyle = this.fillColor;
ctx.fill();
}
if (this.stroke) {
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.strokeColor;
ctx.stroke();
}
ctx.restore();
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class MyAnimation extends MySprite {
frameArr = [];
frameIndex = 0;
playFlag = false;
lastDateTime;
curDelay = 0;
loop = false;
playEndFunc;
delayPerUnit = 1;
restartFlag = false;
reverseFlag = false;
addFrameByImg(img) {
const spr = new MySprite(this.ctx);
spr.init(img);
this._refreshSize(img);
spr.visible = false;
this.addChild(spr);
this.frameArr.push(spr);
this.frameArr[this.frameIndex].visible = true;
}
addFrameByUrl(url) {
const spr = new MySprite(this.ctx);
spr.load(url).then(img => {
this._refreshSize(img);
});
spr.visible = false;
this.addChild(spr);
this.frameArr.push(spr);
this.frameArr[this.frameIndex].visible = true;
}
_refreshSize(img: any) {
if (this.width < img.width) {
this.width = img.width;
}
if (this.height < img.height) {
this.height = img.height;
}
}
play() {
this.playFlag = true;
this.lastDateTime = new Date().getTime();
}
stop() {
this.playFlag = false;
}
replay() {
this.restartFlag = true;
this.play();
}
reverse() {
this.reverseFlag = !this.reverseFlag;
this.frameArr.reverse();
this.frameIndex = 0;
}
showAllFrame() {
for (const frame of this.frameArr ) {
frame.alpha = 1;
}
}
hideAllFrame() {
for (const frame of this.frameArr) {
frame.alpha = 0;
}
}
playEnd() {
this.playFlag = false;
this.curDelay = 0;
this.frameArr[this.frameIndex].visible = true;
if (this.playEndFunc) {
this.playEndFunc();
this.playEndFunc = null;
}
}
updateFrame() {
if (this.frameArr[this.frameIndex]) {
this.frameArr[this.frameIndex].visible = false;
}
this.frameIndex ++;
if (this.frameIndex >= this.frameArr.length) {
if (this.loop) {
this.frameIndex = 0;
} else if (this.restartFlag) {
this.restartFlag = false;
this.frameIndex = 0;
} else {
this.frameIndex -- ;
this.playEnd();
return;
}
}
this.frameArr[this.frameIndex].visible = true;
}
_updateDelay(delay) {
this.curDelay += delay;
if (this.curDelay < this.delayPerUnit) {
return;
}
this.curDelay -= this.delayPerUnit;
this.updateFrame();
}
_updateLastDate() {
if (!this.playFlag) { return; }
let delay = 0;
if (this.lastDateTime) {
delay = (new Date().getTime() - this.lastDateTime) / 1000;
}
this.lastDateTime = new Date().getTime();
this._updateDelay(delay);
}
update($event: any = null) {
super.update($event);
this._updateLastDate();
}
}
// --------=========== util func =============-------------
export function tweenChange(item, obj, time = 0.8, callBack = null, easing = null, update = null) {
const tween = new TWEEN.Tween(item).to(obj, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
if (update) {
tween.onUpdate( (a, b) => {
update(a, b);
});
}
tween.start();
return tween;
}
export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function scaleItem(item, scale, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ scaleX: scale, scaleY: scale}, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.start();
return tween;
}
export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ x, y}, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.start();
return tween;
}
export function endShow(item, s = 1) {
item.scaleX = item.scaleY = 0;
item.alpha = 0;
const tween = new TWEEN.Tween(item)
.to({ alpha: 1, scaleX: s, scaleY: s }, 800)
.easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
})
.start();
}
export function hideItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha === 0) {
return;
}
const tween = new TWEEN.Tween(item)
.to({alpha: 0}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function showItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha === 1) {
if (callBack) {
callBack();
}
return;
}
item.visible = true;
const tween = new TWEEN.Tween(item)
.to({alpha: 1}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item)
.to({alpha}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function showStar(item, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item)
.to({alpha: 1, scale: 1}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function randomSortByArr(arr) {
if (!arr) {
return;
}
const newArr = [];
const tmpArr = arr.concat();
while (tmpArr.length > 0) {
const randomIndex = Math.floor( tmpArr.length * Math.random() );
newArr.push(tmpArr[randomIndex]);
tmpArr.splice(randomIndex, 1);
}
return newArr;
}
export function radianToAngle(radian) {
return radian * 180 / Math.PI;
// 角度 = 弧度 * 180 / Math.PI;
}
export function angleToRadian(angle) {
return angle * Math.PI / 180;
// 弧度= 角度 * Math.PI / 180;
}
export function getPosByAngle(angle, len) {
const radian = angle * Math.PI / 180;
const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len;
return {x, y};
}
export function getAngleByPos(px, py, mx, my) {
const x = Math.abs(px - mx);
const y = Math.abs(py - my);
const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
const cos = y / z;
const radina = Math.acos(cos); // 用反三角函数求弧度
let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度
if (mx > px && my > py) {// 鼠标在第四象限
angle = 180 - angle;
}
if (mx === px && my > py) {// 鼠标在y轴负方向上
angle = 180;
}
if (mx > px && my === py) {// 鼠标在x轴正方向上
angle = 90;
}
if (mx < px && my > py) {// 鼠标在第三象限
angle = 180 + angle;
}
if (mx < px && my === py) {// 鼠标在x轴负方向
angle = 270;
}
if (mx < px && my < py) {// 鼠标在第二象限
angle = 360 - angle;
}
// console.log('angle: ', angle);
return angle;
}
export function removeItemFromArr(arr, item) {
const index = arr.indexOf(item);
if (index !== -1) {
arr.splice(index, 1);
}
}
export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = 1, callBack = null, easing = null) {
const r = getPosDistance(item.x, item.y, x0, y0);
let a = getAngleByPos(item.x, item.y, x0, y0);
a += 90;
const obj = {r, a};
item._circleAngle = a;
const targetA = a + addR;
const tween = new TWEEN.Tween(item).to({_circleAngle: targetA}, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.onUpdate( (item, progress) => {
// console.log(item._circleAngle);
const r = obj.r;
const a = item._circleAngle;
const x = x0 + r * xPer * Math.cos(a * Math.PI / 180);
const y = y0 + r * yPer * Math.sin(a * Math.PI / 180);
item.x = x;
item.y = y;
// obj.a ++;
});
tween.start();
}
export function getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx;
const _y = ey - sy;
const len = Math.sqrt( Math.pow(_x, 2) + Math.pow(_y, 2) );
return len;
}
export function delayCall(callback, second) {
const tween = new TWEEN.Tween(this)
.delay(second * 1000)
.onComplete(() => {
if (callback) {
callback();
}
})
.start();
}
export function formatTime(fmt, date) {
// "yyyy-MM-dd HH:mm:ss";
const o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); }
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1)
? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return fmt;
}
export function getMinScale(item, maxLen) {
const sx = maxLen / item.width;
const sy = maxLen / item.height;
const minS = Math.min(sx, sy);
return minS;
}
export function jelly(item, time = 0.7) {
if (item.jellyTween) {
TWEEN.remove(item.jellyTween);
}
const t = time / 9;
const baseSX = item.scaleX;
const baseSY = item.scaleY;
let index = 0;
const run = () => {
if (index >= arr.length) {
item.jellyTween = null;
return;
}
const data = arr[index];
const t = tweenChange(item, {scaleX: data[0], scaleY: data[1]}, data[2], () => {
index ++;
run();
}, TWEEN.Easing.Sinusoidal.InOut);
item.jellyTween = t;
};
const arr = [
[baseSX * 1.1, baseSY * 0.9, t],
[baseSX * 0.98, baseSY * 1.02, t * 2],
[baseSX * 1.02, baseSY * 0.98, t * 2],
[baseSX * 0.99, baseSY * 1.01, t * 2],
[baseSX * 1.0, baseSY * 1.0, t * 2],
];
run();
}
export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen = 80, showTime = 0.4) {
for (let i = 0; i < num; i ++) {
const particle = new MySprite();
particle.init(img);
particle.x = pos.x;
particle.y = pos.y;
parent.addChild(particle);
const randomR = 360 * Math.random();
particle.rotation = randomR;
const randomS = 0.3 + Math.random() * 0.7;
particle.setScaleXY(randomS * 0.3);
const randomX = Math.random() * 20 - 10;
particle.x += randomX;
const randomY = Math.random() * 20 - 10;
particle.y += randomY;
const randomL = minLen + Math.random() * (maxLen - minLen);
const randomA = 360 * Math.random();
const randomT = getPosByAngle(randomA, randomL);
moveItem(particle, particle.x + randomT.x, particle.y + randomT.y, showTime, () => {
}, TWEEN.Easing.Exponential.Out);
// scaleItem(particle, 0, 0.6, () => {
//
// });
scaleItem(particle, randomS, 0.6, () => {
}, TWEEN.Easing.Exponential.Out);
setTimeout(() => {
hideItem(particle, 0.4, () => {
}, TWEEN.Easing.Cubic.In);
}, showTime * 0.5 * 1000);
}
}
export function shake(item, time = 0.5, callback = null, rate = 1) {
if (item.shakeTween) {
return;
}
item.shakeTween = true;
const offX = 15 * item.scaleX * rate;
const offY = 15 * item.scaleX * rate;
const baseX = item.x;
const baseY = item.y;
const easing = TWEEN.Easing.Sinusoidal.InOut;
const move4 = () => {
moveItem(item, baseX, baseY, time / 4, () => {
item.shakeTween = false;
if (callback) {
callback();
}
}, easing);
};
const move3 = () => {
moveItem(item, baseX + offX / 4, baseY + offY / 4, time / 4, () => {
move4();
}, easing);
};
const move2 = () => {
moveItem(item, baseX - offX / 4 * 3, baseY - offY / 4 * 3, time / 4, () => {
move3();
}, easing);
};
const move1 = () => {
moveItem(item, baseX + offX, baseY + offY, time / 7.5, () => {
move2();
}, easing);
};
}
move1();
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
// --------------- custom class --------------------
export class HotZoneItem extends MySprite {
lineDashFlag = false;
arrow: MySprite;
label: Label;
title;
text;
arrowTop;
arrowRight;
audio_url;
pic_url;
text;
private _itemType;
private shapeRect: ShapeRect;
get itemType() {
return this._itemType;
}
set itemType(value) {
this._itemType = value;
}
setSize(w, h) {
this.width = w;
this.height = h;
const rect = new ShapeRect(this.ctx);
rect.x = -w / 2;
rect.y = -h / 2;
rect.setSize(w, h);
rect.fillColor = '#ffffff';
rect.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 = 40;
this.label.fontSize = '40px';
this.label.textAlign = 'center';
this.addChild(this.label);
// this.label.scaleX = 1 / this.scaleX;
// this.label.scaleY = 1 / this.scaleY;
this.refreshLabelScale();
}
if (text) {
this.label.text = text;
} else if (this.title) {
this.label.text = this.title;
} else if (this.text) {
this.label.text = this.text;
}
this.label.visible = true;
}
hideLabel() {
if (!this.label) { return; }
this.label.visible = false;
}
......@@ -2041,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();
}
......@@ -2060,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();
......@@ -2078,48 +459,28 @@ 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();
......@@ -2127,86 +488,185 @@ export class HotZoneItem extends MySprite {
}
}
export class HotZoneImg extends MySprite {
drawFrame() {
this.ctx.save();
export class HotZoneImageItem extends MySprite {
const rect = this.getBoundingBox();
const w = rect.width;
const h = rect.height;
const x = rect.x + w / 2;
const y = rect.y + h / 2;
lineDashFlag = false;
arrow: MySprite;
label: Label;
image: MySprite;
image_url: String;
labelBox: MySprite;
audio_url: String;
card_audio_url: String
scale
text;
this.ctx.setLineDash([5, 5]);
this.ctx.lineWidth = 2;
this.ctx.strokeStyle = '#1bfff7';
arrowTop;
arrowRight;
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);
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()
})
}
// this.ctx.fill();
this.ctx.stroke();
setSize(w, h) {
this.width = w;
this.height = h;
}
this.ctx.restore();
showLabel(text = null) {
if (!this.label) {
this.labelBox = new MySprite(this.ctx);
this.labelBox.load('assets/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;
}
draw() {
super.draw();
hideLabel() {
if (!this.label) { return; }
this.label.visible = false;
}
this.drawFrame();
showImage(image_url = null, callback) {
this.loadImage(image_url).then((img)=>{
if(this.image){
this.removeChild(this.image)
}
this.image = new MySprite(this.ctx);
this.image.init(img)
this.image.x = this.image.width/2
this.image.y = this.image.height/2
this.image.alpha = 0.7;
this.image_url = image_url;
this.addChild(this.image,-1);
callback && callback(this.image)
})
}
loadImage(image_url = null){
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = image_url;
})
}
}
export class HotZoneLabel extends Label {
hideImage() {
if (!this.image) { return; }
this.image.visible = false;
}
drawFrame() {
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();
}
this.ctx.save();
drawArrow() {
if (!this.arrow) { return; }
const rect = this.getBoundingBox();
const w = rect.width / this.scaleX;
const h = this.height * this.scaleY;
const x = this.x;
const y = this.y;
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.fill();
this.ctx.stroke();
this.ctx.restore();
}
draw() {
super.draw();
if (this.lineDashFlag) {
this.drawFrame();
this.drawArrow();
}
}
}
export class EditorItem extends MySprite {
lineDashFlag = false;
arrow: MySprite;
label: Label;
label:Label;
text;
showLabel(text = null) {
......@@ -2215,7 +675,7 @@ export class EditorItem extends MySprite {
if (!this.label) {
this.label = new Label(this.ctx);
this.label.anchorY = 0;
this.label.fontSize = 50;
this.label.fontSize = '50px';
this.label.textAlign = 'center';
this.addChild(this.label);
this.label.setScaleXY(1 / this.scaleX);
......@@ -2238,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();
......@@ -2326,783 +784,89 @@ export class EditorItem extends MySprite {
//
//
// import TWEEN from '@tweenjs/tween.js';
//
//
// class Sprite {
// x = 0;
// y = 0;
// color = '';
// radius = 0;
// alive = false;
// margin = 0;
// angle = 0;
// ctx;
//
// constructor(ctx) {
// this.ctx = ctx;
// }
// update($event) {
// this.draw();
// }
// draw() {
//
// }
//
// }
//
//
//
//
//
// export class MySprite extends Sprite {
//
// width = 0;
// height = 0;
// _anchorX = 0;
// _anchorY = 0;
// _offX = 0;
// _offY = 0;
// scaleX = 1;
// scaleY = 1;
// alpha = 1;
// rotation = 0;
// visible = true;
//
// children = [this];
//
// 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;
// }
//
//
//
// update($event = null) {
// if (this.visible) {
// this.draw();
// }
// }
// draw() {
//
// this.ctx.save();
//
// this.drawInit();
//
// this.updateChildren();
//
// this.ctx.restore();
// }
//
// drawInit() {
//
// this.ctx.translate(this.x, this.y);
//
// this.ctx.rotate(this.rotation * Math.PI / 180);
//
// this.ctx.scale(this.scaleX, this.scaleY);
//
// this.ctx.globalAlpha = this.alpha;
//
// }
//
// drawSelf() {
// if (this.img) {
// this.ctx.drawImage(this.img, this._offX, this._offY);
// }
// }
//
// updateChildren() {
//
// if (this.children.length <= 0) { return; }
//
// for (let i = 0; i < this.children.length; i++) {
//
// if (this.children[i] === this) {
//
// this.drawSelf();
// } else {
//
// this.children[i].update();
// }
// }
// }
//
//
// load(url, anchorX = 0.5, anchorY = 0.5) {
//
// return new Promise((resolve, reject) => {
// const img = new Image();
// img.onload = () => resolve(img);
// img.onerror = reject;
// img.src = url;
// }).then(img => {
//
// this.init(img, anchorX, anchorY);
// return img;
// });
// }
//
// addChild(child, z = 1) {
// if (this.children.indexOf(child) === -1) {
// this.children.push(child);
// child._z = z;
// child.parent = this;
// }
//
// this.children.sort((a, b) => {
// return a._z - b._z;
// });
//
// }
// removeChild(child) {
// const index = this.children.indexOf(child);
// if (index !== -1) {
// this.children.splice(index, 1);
// }
// }
//
// set anchorX(value) {
// this._anchorX = value;
// this.refreshAnchorOff();
// }
// get anchorX() {
// return this._anchorX;
// }
// set anchorY(value) {
// this._anchorY = value;
// this.refreshAnchorOff();
// }
// get anchorY() {
// return this._anchorY;
// }
// refreshAnchorOff() {
// this._offX = -this.width * this.anchorX;
// this._offY = -this.height * this.anchorY;
// }
//
// setScaleXY(value) {
// this.scaleX = this.scaleY = value;
// }
//
// getBoundingBox() {
//
// const x = this.x + this._offX * this.scaleX;
// const y = this.y + this._offY * this.scaleY;
// const width = this.width * this.scaleX;
// const height = this.height * this.scaleY;
//
// return {x, y, width, height};
// }
//
// }
//
//
//
//
//
// export class Item extends MySprite {
//
// baseX;
//
// move(targetY, callBack) {
//
// const self = this;
//
// const tween = new TWEEN.Tween(this)
// .to({ y: targetY }, 2500)
// .easing(TWEEN.Easing.Quintic.Out)
// .onComplete(function() {
//
// self.hide(callBack);
// // if (callBack) {
// // callBack();
// // }
// })
// .start();
//
// }
//
// show(callBack = null) {
//
// const tween = new TWEEN.Tween(this)
// .to({ alpha: 1 }, 800)
// // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
// .onComplete(function() {
// if (callBack) {
// callBack();
// }
// })
// .start(); // Start the tween immediately.
//
// }
//
// hide(callBack = null) {
//
// const tween = new TWEEN.Tween(this)
// .to({ alpha: 0 }, 800)
// // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
// .onComplete(function() {
// if (callBack) {
// callBack();
// }
// })
// .start(); // Start the tween immediately.
// }
//
//
// shake(id) {
//
//
// if (!this.baseX) {
// this.baseX = this.x;
// }
//
// const baseX = this.baseX;
// const baseTime = 50;
// const sequence = [
// {target: {x: baseX + 40 * id}, time: baseTime - 25},
// {target: {x: baseX - 20 * id}, time: baseTime},
// {target: {x: baseX + 10 * id}, time: baseTime},
// {target: {x: baseX - 5 * id}, time: baseTime},
// {target: {x: baseX + 2 * id}, time: baseTime},
// {target: {x: baseX - 1 * id}, time: baseTime},
// {target: {x: baseX}, time: baseTime},
//
// ];
//
//
// const self = this;
//
// function runSequence() {
//
// if (self['shakeTween']) {
// self['shakeTween'].stop();
// }
//
// const tween = new TWEEN.Tween(self);
//
// if (sequence.length > 0) {
// // console.log('sequence.length: ', sequence.length);
// const action = sequence.shift();
// tween.to(action['target'], action['time']);
// tween.onComplete( () => {
// runSequence();
// });
// tween.start();
//
// self['shakeTween'] = tween;
// }
// }
//
// runSequence();
//
// }
//
//
//
// drop(targetY, callBack = null) {
//
// const self = this;
//
// const time = Math.abs(targetY - this.y) * 2.4;
//
// this.alpha = 1;
//
// const tween = new TWEEN.Tween(this)
// .to({ y: targetY }, time)
// .easing(TWEEN.Easing.Cubic.In)
// .onComplete(function() {
//
// // self.hideItem(callBack);
// if (callBack) {
// callBack();
// }
// })
// .start();
//
//
// }
//
//
// }
//
//
// export class EndSpr extends MySprite {
//
// show(s) {
//
// this.scaleX = this.scaleY = 0;
// this.alpha = 0;
//
// const tween = new TWEEN.Tween(this)
// .to({ alpha: 1, scaleX: s, scaleY: s }, 800)
// .easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
// .onComplete(function() {
//
// })
// .start(); // Start the tween immediately.
//
// }
// }
//
//
//
// export class ShapeRect extends MySprite {
//
// fillColor = '#FF0000';
//
// setSize(w, h) {
// this.width = w;
// this.height = h;
//
// console.log('w:', w);
// console.log('h:', h);
// }
//
// drawShape() {
//
// this.ctx.fillStyle = this.fillColor;
// this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
//
// }
//
//
// drawSelf() {
// super.drawSelf();
// this.drawShape();
// }
// }
//
//
// export class HotZoneItem extends MySprite {
//
//
// lineDashFlag = false;
// arrow: MySprite;
// label: Label;
// title;
//
// arrowTop;
// arrowRight;
//
// audio_url;
// pic_url;
// text;
// private _itemType;
// private shapeRect: ShapeRect;
//
// get itemType() {
// return this._itemType;
// }
// set itemType(value) {
// this._itemType = value;
// }
//
// setSize(w, h) {
// this.width = w;
// this.height = h;
//
//
// const rect = new ShapeRect(this.ctx);
// rect.x = -w / 2;
// rect.y = -h / 2;
// rect.setSize(w, h);
// rect.fillColor = '#ffffff';
// rect.alpha = 0.2;
// this.addChild(rect);
// }
//
// showLabel(text = null) {
//
//
// if (!this.label) {
// this.label = new Label(this.ctx);
// this.label.anchorY = 0;
// this.label.fontSize = '40px';
// this.label.textAlign = 'center';
// this.addChild(this.label);
// // this.label.scaleX = 1 / this.scaleX;
// // this.label.scaleY = 1 / this.scaleY;
//
// this.refreshLabelScale();
//
// }
//
// if (text) {
// this.label.text = text;
// } else if (this.title) {
// this.label.text = this.title;
// }
// this.label.visible = true;
//
// }
//
// hideLabel() {
// if (!this.label) { return; }
//
// this.label.visible = false;
// }
//
// refreshLabelScale() {
// if (this.scaleX == this.scaleY) {
// this.label.setScaleXY(1);
// }
//
// if (this.scaleX > this.scaleY) {
// this.label.scaleX = this.scaleY / this.scaleX;
// } else {
// this.label.scaleY = this.scaleX / this.scaleY;
// }
// }
//
// showLineDash() {
// this.lineDashFlag = true;
//
// if (this.arrow) {
// this.arrow.visible = true;
// } else {
// this.arrow = new MySprite(this.ctx);
// this.arrow.load('assets/common/arrow.png', 1, 0);
// this.arrow.setScaleXY(0.06);
//
// this.arrowTop = new MySprite(this.ctx);
// this.arrowTop.load('assets/common/arrow_top.png', 0.5, 0);
// this.arrowTop.setScaleXY(0.06);
//
// this.arrowRight = new MySprite(this.ctx);
// this.arrowRight.load('assets/common/arrow_right.png', 1, 0.5);
// this.arrowRight.setScaleXY(0.06);
// }
//
// this.showLabel();
// }
//
// hideLineDash() {
//
// this.lineDashFlag = false;
//
// if (this.arrow) {
// this.arrow.visible = false;
// }
//
// this.hideLabel();
// }
//
//
//
// drawArrow() {
// if (!this.arrow) { return; }
//
// const rect = this.getBoundingBox();
// this.arrow.x = rect.x + rect.width;
// this.arrow.y = rect.y;
//
// this.arrow.update();
//
//
// this.arrowTop.x = rect.x + rect.width / 2;
// this.arrowTop.y = rect.y;
// this.arrowTop.update();
//
// this.arrowRight.x = rect.x + rect.width;
// this.arrowRight.y = rect.y + rect.height / 2;
// this.arrowRight.update();
// }
//
// drawFrame() {
//
//
// this.ctx.save();
//
//
// const rect = this.getBoundingBox();
//
// const w = rect.width;
// const h = rect.height;
// const x = rect.x + w / 2;
// const y = rect.y + h / 2;
//
// this.ctx.setLineDash([5, 5]);
// this.ctx.lineWidth = 2;
// this.ctx.strokeStyle = '#1bfff7';
// // this.ctx.fillStyle = '#ffffff';
//
// this.ctx.beginPath();
//
// this.ctx.moveTo( x - w / 2, y - h / 2);
//
// this.ctx.lineTo(x + w / 2, y - h / 2);
//
// this.ctx.lineTo(x + w / 2, y + h / 2);
//
// this.ctx.lineTo(x - w / 2, y + h / 2);
//
// this.ctx.lineTo(x - w / 2, y - h / 2);
//
// // this.ctx.fill();
// this.ctx.stroke();
//
//
//
//
// this.ctx.restore();
//
// }
//
// draw() {
// super.draw();
//
// if (this.lineDashFlag) {
// this.drawFrame();
// this.drawArrow();
// }
// }
// }
//
//
// export class EditorItem extends MySprite {
//
// lineDashFlag = false;
// arrow: MySprite;
// label:Label;
// text;
//
// showLabel(text = null) {
//
//
// if (!this.label) {
// this.label = new Label(this.ctx);
// this.label.anchorY = 0;
// this.label.fontSize = '50px';
// this.label.textAlign = 'center';
// this.addChild(this.label);
// this.label.setScaleXY(1 / this.scaleX);
// }
//
// if (text) {
// this.label.text = text;
// } else if (this.text) {
// this.label.text = this.text;
// }
// this.label.visible = true;
//
// }
//
// hideLabel() {
// if (!this.label) { return; }
//
// this.label.visible = false;
// }
//
// showLineDash() {
// this.lineDashFlag = true;
//
// if (this.arrow) {
// this.arrow.visible = true;
// } else {
// this.arrow = new MySprite(this.ctx);
// this.arrow.load('assets/common/arrow.png', 1, 0);
// this.arrow.setScaleXY(0.06);
//
// }
//
// this.showLabel();
// }
//
// hideLineDash() {
//
// this.lineDashFlag = false;
//
// if (this.arrow) {
// this.arrow.visible = false;
// }
//
// this.hideLabel();
// }
//
//
//
// drawArrow() {
// if (!this.arrow) { return; }
//
// const rect = this.getBoundingBox();
// this.arrow.x = rect.x + rect.width;
// this.arrow.y = rect.y;
//
// this.arrow.update();
// }
//
// drawFrame() {
//
//
// this.ctx.save();
//
//
// const rect = this.getBoundingBox();
//
// const w = rect.width;
// const h = rect.height;
// const x = rect.x + w / 2;
// const y = rect.y + h / 2;
//
// this.ctx.setLineDash([5, 5]);
// this.ctx.lineWidth = 2;
// this.ctx.strokeStyle = '#1bfff7';
// // this.ctx.fillStyle = '#ffffff';
//
// this.ctx.beginPath();
//
// this.ctx.moveTo( x - w / 2, y - h / 2);
//
// this.ctx.lineTo(x + w / 2, y - h / 2);
//
// this.ctx.lineTo(x + w / 2, y + h / 2);
//
// this.ctx.lineTo(x - w / 2, y + h / 2);
//
// this.ctx.lineTo(x - w / 2, y - h / 2);
//
// // this.ctx.fill();
// this.ctx.stroke();
//
//
//
//
// this.ctx.restore();
//
// }
//
// draw() {
// super.draw();
//
// if (this.lineDashFlag) {
// this.drawFrame();
// this.drawArrow();
// }
// }
// }
//
//
//
// export class Label extends MySprite {
//
// text:String;
// fontSize:String = '40px';
// fontName:String = 'Verdana';
// textAlign:String = 'left';
//
//
// constructor(ctx) {
// super(ctx);
// this.init();
// }
//
// drawText() {
//
// // console.log('in drawText', this.text);
//
// if (!this.text) { return; }
//
// this.ctx.font = `${this.fontSize} ${this.fontName}`;
// this.ctx.textAlign = this.textAlign;
// this.ctx.textBaseline = 'middle';
// this.ctx.fontWeight = 900;
//
// this.ctx.lineWidth = 5;
// this.ctx.strokeStyle = '#ffffff';
// this.ctx.strokeText(this.text, 0, 0);
//
// this.ctx.fillStyle = '#000000';
// this.ctx.fillText(this.text, 0, 0);
//
//
// }
//
//
// drawSelf() {
// super.drawSelf();
// this.drawText();
// }
//
// }
//
//
//
// export function getPosByAngle(angle, len) {
//
// const radian = angle * Math.PI / 180;
// const x = Math.sin(radian) * len;
// const y = Math.cos(radian) * len;
//
// return {x, y};
//
// }
//
// export function getAngleByPos(px, py, mx, my) {
//
// // const _x = p2x - p1x;
// // const _y = p2y - p1y;
// // const tan = _y / _x;
// //
// // const radina = Math.atan(tan); // 用反三角函数求弧度
// // const angle = Math.floor(180 / (Math.PI / radina)); //
// //
// // console.log('r: ' , angle);
// // return angle;
// //
//
//
//
// const x = Math.abs(px - mx);
// const y = Math.abs(py - my);
// // const x = Math.abs(mx - px);
// // const y = Math.abs(my - py);
// const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
// const cos = y / z;
// const radina = Math.acos(cos); // 用反三角函数求弧度
// let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度
//
// if(mx > px && my > py) {// 鼠标在第四象限
// angle = 180 - angle;
// }
//
// if(mx === px && my > py) {// 鼠标在y轴负方向上
// angle = 180;
// }
//
// if(mx > px && my === py) {// 鼠标在x轴正方向上
// angle = 90;
// }
//
// if(mx < px && my > py) {// 鼠标在第三象限
// angle = 180 + angle;
// }
//
// if(mx < px && my === py) {// 鼠标在x轴负方向
// angle = 270;
// }
//
// if(mx < px && my < py) {// 鼠标在第二象限
// angle = 360 - angle;
// }
//
// // console.log('angle: ', angle);
// return angle;
//
// }
export class Label extends MySprite {
text:String;
fontSize:String = '40px';
fontName:String = 'Verdana';
textAlign:String = 'left';
constructor(ctx) {
super(ctx);
this.init();
}
drawText() {
if (!this.text) { return; }
this.ctx.font = `${this.fontSize} ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = 900;
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = '#ffffff';
this.ctx.strokeText(this.text, 0, 0);
this.ctx.fillStyle = '#000000';
this.ctx.fillText(this.text, 0, 0);
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export function getPosByAngle(angle, len) {
const radian = angle * Math.PI / 180;
const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len;
return {x, y};
}
export function getAngleByPos(px, py, mx, my) {
const x = Math.abs(px - mx);
const y = Math.abs(py - my);
const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
const cos = y / z;
const radina = Math.acos(cos); // 用反三角函数求弧度
let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度
if(mx > px && my > py) {// 鼠标在第四象限
angle = 180 - angle;
}
if(mx === px && my > py) {// 鼠标在y轴负方向上
angle = 180;
}
if(mx > px && my === py) {// 鼠标在x轴正方向上
angle = 90;
}
if(mx < px && my > py) {// 鼠标在第三象限
angle = 180 + angle;
}
if(mx < px && my === py) {// 鼠标在x轴负方向
angle = 270;
}
if(mx < px && my < py) {// 鼠标在第二象限
angle = 360 - angle;
}
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 nz-row nzType="flex" nzAlign="middle">
<div nz-col nzSpan="5" nzOffset="1">
<h5> add background: </h5>
<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>
<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="margin: auto; padding: 5px; margin-top: 30px; width:90%; border: 2px dashed #ddd; border-radius: 10px">
<span style="margin-left: 40%;"> item-{{i + 1}}
</span>
<button style="float: right;" nz-button nzType="danger" nzSize="small" (click)="deleteBtnClick(i)">
X
</button>
<nz-divider style="margin-top: 10px;"></nz-divider>
<div style="margin-top: -20px; margin-bottom: 5px">
<nz-radio-group [ngModel]="it.itemType" (ngModelChange)="radioChange($event, it)">
<label *ngIf="isHasRect" nz-radio nzValue="rect">矩形</label>
<label *ngIf="isHasPic" nz-radio nzValue="pic">图片</label>
<label *ngIf="isHasText" nz-radio nzValue="text">文本</label>
</nz-radio-group>
</div>
<div *ngIf="it.itemType == 'pic'">
<app-upload-image-with-preview
[picUrl]="it?.pic_url"
(imageUploaded)="onItemImgUploadSuccess($event, it)">
</app-upload-image-with-preview>
<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 *ngIf="it.itemType == 'text'">
<input type="text" nz-input [(ngModel)]="it.text" (blur)="saveText(it)">
</div>
<div style="width: 100%; margin-top: 5px;">
<app-audio-recorder
[audioUrl]="it.audio_url"
(audioUploaded)="onItemAudioUploadSuccess($event, it)"
></app-audio-recorder>
<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>
<label style="opacity: 0; position: absolute; top: 0px; font-family: 'BRLNSR_1'">1</label>
.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,28 +72,6 @@ h5 {
margin-top: 1rem;
}
@font-face
{
font-family: 'BRLNSR_1';
src: url("/assets/font/BRLNSR_1.TTF") ;
}
//@import '../../../style/common_mixin';
//
//.p-image-uploader {
......
import {
Component,
ElementRef,
EventEmitter,
HostListener,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
ViewChild
} from '@angular/core';
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, HotZoneImg, HotZoneItem, HotZoneLabel, Label, MySprite, removeItemFromArr} from './Unit';
import {EditorItem, HotZoneImageItem, Label, MySprite} from './Unit';
import TWEEN from '@tweenjs/tween.js';
import {getMinScale} from "../../play/Unit";
import {tar} from "compressing";
@Component({
......@@ -26,199 +13,188 @@ import {tar} from "compressing";
export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
_bgItem = null;
@Input()
set bgItem(v) {
this._bgItem = v;
this.init();
}
get bgItem() {
return this._bgItem;
}
@Input()
imgItemArr = null;
@Input()
hotZoneItemArr = null;
@Input()
hotZoneArr = null;
@Output()
save = new EventEmitter();
@ViewChild('canvas', {static: true}) canvas: ElementRef;
@ViewChild('wrap', {static: true}) wrap: ElementRef;
@Input()
isHasRect = true;
@Input()
isHasPic = true;
@Input()
isHasText = true;
@Input()
hotZoneFontObj = {
size: 50,
name: 'BRLNSR_1',
color: '#8f3758'
@ViewChild('canvas', {static: true }) canvas: ElementRef;
@ViewChild('wrap', {static: true }) wrap: ElementRef;
@HostListener('window:resize', ['$event'])
onResize(event) {
this.g_winResizeEventStream.next();
}
@Input()
defaultItemType = 'text';
@Input()
hotZoneImgSize = 190;
saveDisabled = true;
g_winResizeEventStream = new Subject();
canvasWidth = 1280;
canvasHeight = 720;
canvasBaseW = 1280;
// @HostListener('window:resize', ['$event'])
canvasBaseH = 720;
mapScale = 1;
ctx;
mx;
my; // 点击坐标
// 资源
// rawImages = new Map(res);
// 声音
bgAudio = new Audio();
images = new Map();
animationId: any;
animationId: any;
// winResizeEventStream = new Subject();
// 资源
// rawImages = new Map(res);
winResizeEventStream = new Subject();
canvasLeft;
canvasTop;
renderArr;
imgArr = [];
oldPos;
radioValue;
curItem;
bg: MySprite;
changeSizeFlag = false;
changeTopSizeFlag = false;
changeRightSizeFlag = false;
hotZoneChanged = false;
scale = 1;
constructor() {
}
_bgItem = null;
get bgItem() {
return this._bgItem;
}
@Input()
set bgItem(v) {
this._bgItem = v;
this.init();
}
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();
}
onItemImgUploadSuccess(e, item) {
item.pic_url = e.url;
this.loadHotZonePic(item.pic, e.url);
}
onItemAudioUploadSuccess(e, item) {
item.audio_url = e.url;
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.refreshItem(item);
this.refreshHotZoneId();
this.autoSave()
}
deleteBtnClick(index) {
const item = this.hotZoneArr.splice(index, 1)[0];
removeItemFromArr(this.renderArr, item.pic);
removeItemFromArr(this.renderArr, item.textLabel);
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()
}
this.refreshHotZoneId();
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()
}
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()
}
onImgUploadSuccessByImg(e, img) {
img.pic_url = e.url;
this.refreshImage(img);
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].title = 'item-' + (i + 1);
this.hotZoneArr[i].text = (i + 1);
}
}
}
......@@ -227,78 +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;
item.itemType = this.defaultItemType;
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();
const pic = new HotZoneImg(this.ctx);
pic.visible = false;
item['pic'] = pic;
if (saveData && saveData.pic_url) {
this.loadHotZonePic(pic, saveData.pic_url);
}
pic.x = item.x;
pic.y = item.y;
this.renderArr.push(pic);
const textLabel = new HotZoneLabel(this.ctx);
textLabel.fontSize = this.hotZoneFontObj.size;
textLabel.fontName = this.hotZoneFontObj.name;
textLabel.fontColor = this.hotZoneFontObj.color;
textLabel.textAlign = 'center';
// textLabel.setOutline();
// console.log('saveData:', saveData);
item['textLabel'] = textLabel;
textLabel.setScaleXY(this.mapScale);
if (saveData && saveData.text) {
textLabel.text = saveData.text;
textLabel.refreshSize();
}
textLabel.x = item.x;
textLabel.y = item.y;
this.renderArr.push(textLabel);
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 => {
item.load(img.pic_url).then( img => {
let maxW, maxH;
if (this.bg) {
maxW = this.bg.width * this.bg.scaleX;
......@@ -307,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 {
......@@ -318,66 +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.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()
}
radioChange(e, item) {
item.itemType = e;
this.refreshItem(item);
// console.log(' in radioChange e: ', e);
}
refreshItem(item) {
switch (item.itemType) {
case 'rect':
this.setRectState(item);
break;
case 'pic':
this.setPicState(item);
break;
case 'text':
this.setTextState(item);
break;
default:
}
}
init() {
this.initData();
this.initCtx();
this.initItem();
}
......@@ -386,86 +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);
item.audio_url = data.audio_url;
item.pic_url = data.pic_url;
item.text = data.text;
item.itemType = data.itemType;
this.refreshItem(item);
console.log('item: ', item);
// 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();
......@@ -479,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++) {
......@@ -506,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 = [];
}
......@@ -525,43 +388,31 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
mapDown(event) {
this.oldPos = {x: this.mx, y: this.my};
for (let i = 0; i < this.hotZoneArr.length; i++) {
const item = this.hotZoneArr[i];
let callback;
let target;
switch (item.itemType) {
case 'rect':
target = item;
callback = this.clickedHotZoneRect.bind(this);
break;
case 'pic':
target = item.pic;
callback = this.clickedHotZonePic.bind(this);
break;
case 'text':
target = item.textLabel;
callback = this.clickedHotZoneText.bind(this);
break;
}
if (this.checkClickTarget(target)) {
callback(target);
return;
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)) {
this.changeItemTopSize(item);
} else if (item.lineDashFlag && this.checkClickTarget(item.arrowRight)) {
this.changeItemRightSize(item);
} else {
this.changeCurItem(item);
}
this.hotZoneChanged = true;
return;
}
}
}
}
mapMove(event) {
if (!this.curItem) {
return;
}
if (!this.curItem) { return; }
if (this.changeSizeFlag) {
this.changeSize();
......@@ -571,19 +422,14 @@ 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;
}
this.oldPos = {x: this.mx, y: this.my};
this.saveDisabled = true;
}
mapUp(event) {
......@@ -594,78 +440,52 @@ 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;
changeSize() {
const rect = this.curItem.getBoundingBox();
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) {
......@@ -702,30 +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);
this.updatePos()
TWEEN.update();
}
......@@ -737,23 +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.g_winResizeEventStream.pipe(debounceTime(500)).subscribe(data => {
this.renderAfterResize();
});
if (this.IsPC()) {
this.canvas.nativeElement.addEventListener('mousedown', (event) => {
setMxMyByMouse(event);
this.mapDown(event);
......@@ -801,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;
......@@ -833,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;
......@@ -850,137 +644,41 @@ 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();
} else {
bgItem['rect'] = {
x: 0,
y: 0,
width: Math.round(this.canvasWidth * 100) / 100,
height: Math.round(this.canvasHeight * 100) / 100
};
bgItem['rect'] = {x: 0, y: 0, width: Math.round(this.canvasWidth * 100) / 100, height: Math.round(this.canvasHeight * 100) / 100};
}
const hotZoneItemArr = [];
const hotZoneArr = this.hotZoneArr;
for (let i = 0; i < hotZoneArr.length; i++) {
const hotZoneItem = {
index: hotZoneArr[i].index,
pic_url: hotZoneArr[i].pic_url,
text: hotZoneArr[i].text,
audio_url: hotZoneArr[i].audio_url,
itemType: hotZoneArr[i].itemType,
fontSize: this.hotZoneFontObj.size,
fontName: this.hotZoneFontObj.name,
fontColor: this.hotZoneFontObj.color,
fontScale: hotZoneArr[i].textLabel ? hotZoneArr[i].textLabel.scaleX : 1,
imgScale: hotZoneArr[i].pic ? hotZoneArr[i].pic.scaleX : 1,
mapScale: this.mapScale
};
hotZoneItem['rect'] = hotZoneArr[i].getBoundingBox();
hotZoneItem['rect'].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;
}
private updatePos() {
this.hotZoneArr.forEach((item) => {
let x, y;
switch (item.itemType) {
case 'rect':
x = item.x;
y = item.y;
break;
case 'pic':
x = item.pic.x;
y = item.pic.y;
break;
case 'text':
x = item.textLabel.x;
y = item.textLabel.y;
break;
}
item.x = x;
item.y = y;
item.pic.x = x;
item.pic.y = y;
item.textLabel.x = x;
item.textLabel.y = y;
});
}
private setPicState(item: any) {
item.visible = false;
item.textLabel.visible = false;
item.pic.visible = true;
}
private setRectState(item: any) {
item.visible = true;
item.textLabel.visible = false;
item.pic.visible = false;
}
private setTextState(item: any) {
item.visible = false;
item.pic.visible = false;
item.textLabel.visible = true;
}
private clickedHotZoneRect(item: any) {
if (this.checkClickTarget(item)) {
if (item.lineDashFlag && this.checkClickTarget(item.arrow)) {
this.changeItemSize(item);
} else if (item.lineDashFlag && this.checkClickTarget(item.arrowTop)) {
this.changeItemTopSize(item);
} else if (item.lineDashFlag && this.checkClickTarget(item.arrowRight)) {
this.changeItemRightSize(item);
} else {
this.changeCurItem(item);
}
return;
}
}
private clickedHotZonePic(item: any) {
if (this.checkClickTarget(item)) {
this.curItem = item;
}
}
private clickedHotZoneText(item: any) {
if (this.checkClickTarget(item)) {
this.curItem = item;
}
}
saveText(item) {
item.textLabel.text = item.text;
}
private loadHotZonePic(pic: HotZoneImg, url) {
const baseLen = this.hotZoneImgSize * this.mapScale;
pic.load(url).then(() => {
const s = getMinScale(pic, baseLen);
pic.setScaleXY(s);
});
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', {static: true }) 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%;
......
......@@ -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-icon name="cloud-upload"></fa-icon>
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 {
......
......@@ -29,19 +29,10 @@ export class UploadImageWithPreviewComponent implements OnDestroy, OnChanges {
@Input()
disableUpload = false;
uploadUrl;
uploadData;
uploadUrl = (<any> window).courseware.uploadUrl();
uploadData = (<any> window).courseware.uploadData();
constructor(private nzMessageService: NzMessageService) {
this.uploadUrl = (<any> window).courseware.uploadUrl();
this.uploadData = (<any> window).courseware.uploadData();
window['air'].getUploadCallback = (url, data) => {
this.uploadUrl = url;
this.uploadData = data;
};
}
ngOnChanges() {
if (!this.picItem) {
......@@ -54,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-icon name="cloud-upload"></fa-icon>
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-icon name="cloud-upload"></fa-icon>
<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';
......@@ -47,8 +47,8 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
item: any;
// videoItem = null;
uploadUrl;
uploadData;
uploadUrl = (<any> window).courseware.uploadUrl();
uploadData = (<any> window).courseware.uploadData();
constructor(private nzMessageService: NzMessageService,
private sanitization: DomSanitizer
......@@ -58,16 +58,6 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
this.uploading = false;
this.videoFile = null;
this.uploadUrl = (<any> window).courseware.uploadUrl();
this.uploadData = (<any> window).courseware.uploadData();
window['air'].getUploadCallback = (url, data) => {
this.uploadUrl = url;
this.uploadData = data;
};
}
ngOnChanges() {
// if (!this.videoFile || this.showUploadBtn) {
......@@ -81,7 +71,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
}
safeVideoUrl(url) {
console.log(url);
console.log(url)
return this.sanitization.bypassSecurityTrustResourceUrl(url); // `${url}`;
}
videoLoadedMetaData() {
......@@ -89,7 +79,7 @@ export class UploadVideoComponent implements OnChanges, OnDestroy {
}
handleChange(info: UploadChangeParam/* { type: string, file: UploadFile, event: any }*/): void {
handleChange(info: { type: string, file: UploadFile, event: any }): void {
console.log('info:' , info);
......@@ -119,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;
}
......@@ -162,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();
......
......@@ -6,3 +6,30 @@
height: 100%;
}
.radioPaire {
float: left;
margin: 3px;
border-style: dashed;
border-color: #000;
border-width: 1px;
}
.border {
border-radius: 20px;
border-style: dashed;
padding: 20px;
margin: 20px;
/*width: 500px; */
/*//border-radius: 20px;*/
/*//border-width: 2px;*/
/*//border-color: #000000;*/
}
.border-lite {
border: 2px dashed #ddd;
border-radius: 0.5rem;
padding: 10px;
margin: 10px;
}
<div class="model-content" style="padding: 10px">
<div style="width: 300px; margin-top: 15px">
<span>请输入标题: </span>
<input type="text" nz-input [(ngModel)]="item.title" (blur)="save()" />
</div>
<div class="model-content">
<div style="margin-top: 15px;display:none">
<span>标题音频: </span>
<app-audio-recorder
[audioUrl]="item.audio_title"
(audioUploaded)="onAudioUploadSuccess($event, 'audio_title')"
></app-audio-recorder>
</div>
<div style="margin-top: 25px">选择样式:</div>
<div style="position: absolute; left: 200px; top: 100px; width: 800px;">
<nz-radio-group
[(ngModel)]="type"
name="radioValue"
id="radioValue"
(ngModelChange)="onSetType()"
style="width: 60%"
>
<div *ngFor="let style of styles" style="width: 50%; float: left; text-align: center">
<span>{{ style.name }}</span>
<br />
<br />
<img
[alt]="style.name"
[src]="style.image"
style="width: 200px; height: auto"
/>
<br />
<span>(示例)</span>
<br />
<br />
<span>选择 </span><label nz-radio [nzValue]="style.id" (blur)="save()"></label>
</div>
</nz-radio-group>
<input type="text" nz-input [(ngModel)]="item.text" (blur)="save()">
<div class="border" style="width: 90%; height: 1600px" *ngIf="type == 0">
<div style="width: 100%; text-align: center">
<h3>样式1</h3>
</div>
<div style="float: left; width: 30%">
<div style="margin-top: 255px">
<strong>左侧字母:</strong>
<input
type="text"
nz-input
[(ngModel)]="dataType.single.words"
(blur)="onSaveWord('single')"
style="width: 20%"
maxlength="2"
/>
<app-upload-image-with-preview
[picUrl]="item.pic_url"
(imageUploaded)="onImageUploadSuccess($event, 'pic_url')"
></app-upload-image-with-preview>
<div
*ngFor="let word of dataType['single'].wordArr; let j = index"
>
<div *ngIf="word.type == 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
color: #000000;
margin-right: 2px;
"
(click)="onUpWordClicked('single', j)"
>{{ word.word }}</a
>
</div>
<div *ngIf="word.type != 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
border-bottom-width: 3px;
border-bottom-color: #000000;
border-bottom-style: solid;
color: #c8161e;
margin-right: 2px;
"
(click)="onUpWordClicked('single', j)"
>{{ word.word }}</a
>
</div>
</div>
<br />
<br />
<br />
<br />
<span>(点击字母设置为高亮显示)</span>
<br />
<br />
<span>音频: </span>
<app-audio-recorder
[audioUrl]="item.audio_url"
(audioUploaded)="onAudioUploadSuccess($event, 'audio_url')"
[audioUrl]="dataType.single_audio"
(audioUploaded)="
onAudioUploadSuccessByItem($event, dataType, 'single_audio')
"
></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>
<br />
<span>默认显示: </span>
<label nz-checkbox [(ngModel)]="dataType.single_show" (ngModelChange)="save()"></label>
</div>
</div>
<div style="float: right; width: 40%">
<div *ngFor="let index of doubleLetterIndexes" style="margin-top: 30px">
<strong>右侧字母-{{index+1}}:</strong>
<input
type="text"
nz-input
[(ngModel)]="dataType['character_'+index+index].words"
(blur)="onSaveWord('character_'+index+index)"
style="width: 15%"
maxlength="4"
/>
</div>
<div
*ngFor="let word of dataType['character_'+index+index].wordArr; let j = index"
>
<div *ngIf="word.type == 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
color: #000000;
margin-right: 2px;
"
(click)="onUpWordClicked('character_'+index+index, j)"
>{{ word.word }}</a
>
</div>
<div *ngIf="word.type != 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
border-bottom-width: 3px;
border-bottom-color: #000000;
border-bottom-style: solid;
color: #c8161e;
margin-right: 2px;
"
(click)="onUpWordClicked('character_'+index+index, j)"
>{{ word.word }}</a
>
</div>
</div>
<br />
<br />
<br />
<br />
<span>(点击字母设置为高亮显示)</span>
<br />
<br />
<span>音频: </span>
<app-audio-recorder
[audioUrl]="dataType['character_'+index+index+'_audio']"
(audioUploaded)="
onAudioUploadSuccessByItem($event, dataType, 'character_'+index+index+'_audio')
"
></app-audio-recorder>
<br />
<span>默认显示: </span>
<label nz-checkbox [(ngModel)]="dataType['character_'+index+index+'_show']" (ngModelChange)="save()"></label>
</div>
</div>
<div style="float: right; width: 30%">
<div *ngFor="let index of singleLetterIndexes" style="margin-top: 30px">
<strong>中间字母-{{index+1}}:</strong>
<input
type="text"
nz-input
[(ngModel)]="dataType['character_'+index].words"
(blur)="onSaveWord('character_'+index)"
style="width: 20%"
maxlength="2"
/>
<div
*ngFor="let word of dataType['character_'+index].wordArr; let j = index"
>
<div *ngIf="word.type == 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
color: #000000;
margin-right: 2px;
"
(click)="onUpWordClicked('character_'+index, j)"
>{{ word.word }}</a
>
</div>
<div *ngIf="word.type != 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
border-bottom-width: 3px;
border-bottom-color: #000000;
border-bottom-style: solid;
color: #c8161e;
margin-right: 2px;
"
(click)="onUpWordClicked('character_'+index, j)"
>{{ word.word }}</a
>
</div>
</div>
<br />
<br />
<br />
<br />
<span>(点击字母设置为高亮显示)</span>
<br />
<br />
<span>音频: </span>
<app-audio-recorder
[audioUrl]="dataType['character_'+index+'_audio']"
(audioUploaded)="
onAudioUploadSuccessByItem($event, dataType, 'character_'+index+'_audio')
"
></app-audio-recorder>
<br />
<span>默认显示: </span>
<label nz-checkbox [(ngModel)]="dataType['character_'+index+'_show']" (ngModelChange)="save()"></label>
</div>
</div>
</div>
<div class="border" style="width: 90%; height: 1600px" *ngIf="type == 1">
<div style="width: 100%; text-align: center">
<h3>样式2</h3>
</div>
<div style="float: right; width: 40%">
<div *ngFor="let index of doubleLetterIndexes" style="margin-top: 30px">
<strong>右侧字母-{{index+1}}:</strong>
<input
type="text"
nz-input
[(ngModel)]="dataType['character_'+index+index].words"
(blur)="onSaveWord('character_'+index+index)"
style="width: 15%"
maxlength="4"
/>
<div
*ngFor="let word of dataType['character_'+index+index].wordArr; let j = index"
>
<div *ngIf="word.type == 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
color: #000000;
margin-right: 2px;
"
(click)="onUpWordClicked('character_'+index+index, j)"
>{{ word.word }}</a
>
</div>
<div *ngIf="word.type != 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
border-bottom-width: 3px;
border-bottom-color: #000000;
border-bottom-style: solid;
color: #c8161e;
margin-right: 2px;
"
(click)="onUpWordClicked('character_'+index+index, j)"
>{{ word.word }}</a
>
</div>
</div>
<br />
<br />
<br />
<br />
<span>(点击字母设置为高亮显示)</span>
<br />
<br />
<span>音频: </span>
<app-audio-recorder
[audioUrl]="dataType['character_'+index+index+'_audio']"
(audioUploaded)="
onAudioUploadSuccessByItem($event, dataType, 'character_'+index+index+'_audio')
"
></app-audio-recorder>
<br />
<span>默认显示: </span>
<label nz-checkbox [(ngModel)]="dataType['character_'+index+index+'_show']" (ngModelChange)="save()"></label>
</div>
</div>
<div style="float: right; width: 30%">
<div style="margin-top: 255px">
<strong>中间字母:</strong>
<input
type="text"
nz-input
[(ngModel)]="dataType.single.words"
(blur)="onSaveWord('single')"
style="width: 20%"
maxlength="2"
/>
<div
*ngFor="let word of dataType['single'].wordArr; let j = index"
>
<div *ngIf="word.type == 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
color: #000000;
margin-right: 2px;
"
(click)="onUpWordClicked('single', j)"
>{{ word.word }}</a
>
</div>
<div *ngIf="word.type != 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
border-bottom-width: 3px;
border-bottom-color: #000000;
border-bottom-style: solid;
color: #c8161e;
margin-right: 2px;
"
(click)="onUpWordClicked('single', j)"
>{{ word.word }}</a
>
</div>
</div>
<br />
<br />
<br />
<br />
<span>(点击字母设置为高亮显示)</span>
<br />
<br />
<span>音频: </span>
<app-audio-recorder
[audioUrl]="dataType.single_audio"
(audioUploaded)="
onAudioUploadSuccessByItem($event, dataType, 'single_audio')
"
></app-audio-recorder>
<br />
<span>默认显示: </span>
<label nz-checkbox [(ngModel)]="dataType.single_show" (ngModelChange)="save()"></label>
</div>
</div>
<div style="float: left; width: 30%">
<div *ngFor="let index of singleLetterIndexes" style="margin-top: 30px">
<strong>左侧字母-{{index+1}}:</strong>
<input
type="text"
nz-input
[(ngModel)]="dataType['character_'+index].words"
(blur)="onSaveWord('character_'+index)"
style="width: 20%"
maxlength="2"
/>
<div
*ngFor="let word of dataType['character_'+index].wordArr; let j = index"
>
<div *ngIf="word.type == 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
color: #000000;
margin-right: 2px;
"
(click)="onUpWordClicked('character_'+index, j)"
>{{ word.word }}</a
>
</div>
<div *ngIf="word.type != 'normal'" style="float: left">
<a
style="
float: left;
font-size: 42px;
font-family: FuturaBT-Bold;
border-bottom-width: 3px;
border-bottom-color: #000000;
border-bottom-style: solid;
color: #c8161e;
margin-right: 2px;
"
(click)="onUpWordClicked('character_'+index, j)"
>{{ word.word }}</a
>
</div>
</div>
<br />
<br />
<br />
<br />
<span>(点击字母设置为高亮显示)</span>
<br />
<br />
<span>音频: </span>
<app-audio-recorder
[audioUrl]="dataType['character_'+index+'_audio']"
(audioUploaded)="
onAudioUploadSuccessByItem($event, dataType, 'character_'+index+'_audio')
"
></app-audio-recorder>
<br />
<span>默认显示: </span>
<label nz-checkbox [(ngModel)]="dataType['character_'+index+'_show']" (ngModelChange)="save()"></label>
</div>
</div>
</div>
</div>
import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef} from '@angular/core';
import {
Component,
EventEmitter,
Input,
OnDestroy,
OnChanges,
OnInit,
Output,
ApplicationRef,
ChangeDetectorRef,
} from "@angular/core";
import { JsonPipe } from "@angular/common";
import { log } from "ng-zorro-antd";
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
selector: "app-form",
templateUrl: "./form.component.html",
styleUrls: ["./form.component.css"],
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
// 储存数据用
saveKey = "test_0011";
saveKey = "ssiwb2501";
// 储存对象
item;
constructor(private appRef: ApplicationRef,private changeDetectorRef: ChangeDetectorRef) {
type = 0;
dataType;
// 样式选项
styles = [
{ id: 0, name: '样式1', image: 'http://staging-teach.cdn.ireadabc.com/b41bf63c28c65bc46c3a1ae77e70cb75.png' },
{ id: 1, name: '样式2', image: 'http://staging-teach.cdn.ireadabc.com/49f2cb0d2b76bf866788a2c0244af69e.png' }
];
// 字母索引数组
singleLetterIndexes = [0, 1, 2, 3, 4]; // 对应character_0到character_4
doubleLetterIndexes = [0, 1, 2, 3, 4]; // 对应character_00到character_44
constructor(
private appRef: ApplicationRef,
private changeDetectorRef: ChangeDetectorRef
) {}
createShell() {
this.item.wordList.push({
word: "",
audio: "",
backWord: "",
backWordAudio: "",
});
this.save();
}
removeShell(idx) {
this.item.wordList.splice(idx, 1);
this.save();
}
ngOnInit() {
this.item = {};
this.item = { title: "", audio_title: "" };
this.dataType = {
single: { words: "", wordArr: [] },
single_audio: "",
single_show: true,
character_00: { words: "", wordArr: [] },
character_11: { words: "", wordArr: [] },
character_22: { words: "", wordArr: [] },
character_33: { words: "", wordArr: [] },
character_44: { words: "", wordArr: [] },
character_0: { words: "", wordArr: [] },
character_1: { words: "", wordArr: [] },
character_2: { words: "", wordArr: [] },
character_3: { words: "", wordArr: [] },
character_4: { words: "", wordArr: [] },
character_0_show: true,
character_1_show: true,
character_2_show: true,
character_3_show: true,
character_4_show: true,
character_00_show: true,
character_11_show: true,
character_22_show: true,
character_33_show: true,
character_44_show: true,
};
this.type = 0;
// 获取存储的数据
(<any> window).courseware.getData((data) => {
(<any>window).courseware.getData((data) => {
if (data) {
this.item = data;
}
......@@ -35,31 +94,28 @@ export class FormComponent implements OnInit, OnChanges, OnDestroy {
this.changeDetectorRef.markForCheck();
this.changeDetectorRef.detectChanges();
this.refresh();
}, this.saveKey);
}
ngOnChanges() {
}
ngOnDestroy() {
}
ngOnChanges() {}
ngOnDestroy() {}
init() {
if (this.item.type) {
this.type = this.item.type;
}
// 加载数据
if (this.item.dataType) {
this.dataType = this.item.dataType;
}
}
/**
* 储存图片数据
* @param e
*/
onImageUploadSuccess(e, key) {
this.item[key] = e.url;
this.save();
}
......@@ -69,19 +125,59 @@ export class FormComponent implements OnInit, OnChanges, OnDestroy {
* @param e
*/
onAudioUploadSuccess(e, key) {
this.item[key] = e.url;
this.save();
}
onAudioUploadSuccessByItem(e, it, key) {
it[key] = e.url;
this.save();
}
onWordAudioUploadSuccess(e, idx) {
this.item.wordList[idx].audio = e.url;
this.save();
}
onBackWordAudioUploadSuccess(e, idx) {
this.item.wordList[idx].backWordAudio = e.url;
this.save();
}
onUpWordClicked(key, index) {
if (this.dataType[key].wordArr[index].type == "normal") {
this.dataType[key].wordArr[index].type = "red";
} else {
this.dataType[key].wordArr[index].type = "normal";
}
this.save();
}
onSaveWord(key) {
// console.log(this.dataType);
let res = [];
let words = this.dataType[key].words.split("");
for (let w of words) {
res.push({ word: w, type: "normal" });
}
this.dataType[key].wordArr = res;
this.save();
}
/**
* 储存数据
*/
save() {
(<any> window).courseware.setData(this.item, null, this.saveKey);
this.item.type = this.type;
this.item.dataType = this.dataType;
(<any>window).courseware.setData(this.item, null, this.saveKey);
this.refresh();
console.log("this.item = " + JSON.stringify(this.item));
}
/**
......@@ -93,5 +189,7 @@ export class FormComponent implements OnInit, OnChanges, OnDestroy {
}, 1);
}
onSetType() {
this.save();
}
}
import {
MySprite,
getMinScale,
ShapeRect,
tweenChange,
randomSortByArr,
Label,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem,
ShapeRectNew
} from "./Unit";
import { CartoonAnimation } from './CartoonAnimation'
/**
* Cartoon 类
* 用于管理动画元素、资源加载和播放的核心类
* 提供了坐标系统、资源管理、元素创建和位置控制等功能
*/
export class Cartoon {
// 系统缩放比例
mapScale = 1;
// 舞台宽度
stageWidth;
// 舞台高度
stageHeight;
// 客户端宽度
clientWidth;
// 客户端高度
clientHeight;
// 音乐 和 图片的缓冲区
audio = new Map(); // 存储音频对象的Map
images = new Map(); // 存储图像对象的Map
imagesOriginSize = new Map(); // 存储图像原始尺寸的Map
// 坐标原点 包含缩放
// 用于全局坐标系的原点位置
originX = 0;
originY = 0;
/**
* 设置全局坐标原点
* @param x - X坐标
* @param y - Y坐标
*/
setOrigin = (x, y)=>{
this.originX = x;
this.originY = y;
}
/**
* 获取全局坐标原点
* @returns {{x: number, y: number}} 坐标原点对象
*/
getOrigin = ()=>{
return {
x: this.originX,
y: this.originY
}
}
// 相对坐标原点 包含缩放 用于添加孩子动画元素
relativeOriginX = 0;
relativeOriginY = 0;
/**
* 设置相对坐标原点
* 用于子元素相对于父元素的定位
* @param x - X坐标
* @param y - Y坐标
*/
setRelativeOrigin = (x, y)=>{
this.relativeOriginX = x;
this.relativeOriginY = y;
}
/**
* 获取相对坐标原点
* @returns {{x: number, y: number}} 相对坐标原点对象
*/
getRelativeOrigin = ()=>{
return {
x: this.relativeOriginX,
y: this.relativeOriginY
}
}
// 存放音乐和图片的地址
audioObj = {} // 音频URL对象,键为音频ID,值为URL
imageObj = {} // 图像URL对象,键为图像ID,值为URL
_currentPlayAudio; // 当前播放的音频对象
/**
* 添加音频资源
* @param key - 音频资源的唯一标识符
* @param url - 音频资源的URL地址
*/
addAudio = ( key, url ) => {
this.audioObj[key] = url
};
/**
* 添加图像资源
* @param key - 图像资源的唯一标识符
* @param url - 图像资源的URL地址
*/
addImage = ( key, url ) => {
this.imageObj[key] = url
};
// 当前正在播放的音频列表
_playingNow = []
/**
* 播放音频
* @param key - 要播放的音频资源的唯一标识符
* @param now - 是否立即播放(重置当前播放进度),默认为false
* @param callback - 音频播放完成后的回调函数,默认为null
*/
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;
}
}
/**
* 停止所有正在播放的音频
* 会触发所有音频的onended回调
*/
stopAllAudio(){
this._playingNow.forEach(audio=>{
try{
// 触发音频结束回调
audio.onended && audio.onended()
// 暂停并重置播放进度
audio.pause();
audio.currentTime = 0;
}catch(err){
console.log(err)
}
})
// 清空正在播放列表
this._playingNow = []
}
/**
* 停止当前播放的音频
* 只停止最后一个通过playAudio播放的音频
*/
stopAudio(){
if(this._currentPlayAudio){
this._currentPlayAudio.pause();
this._currentPlayAudio.currentTime = 0;
}
}
/**
* 异步加载所有图片和音频资源
* 将所有资源的加载Promise合并为一个Promise
* @returns {Promise<any[]>} 所有资源加载完成的Promise
*/
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);
};
// 返回所有资源加载的Promise
return Promise.all(pr);
}
/**
* 预加载单个图像
* @param url - 图像的URL地址
* @returns {Promise<Image>} 加载完成的Image对象Promise
*/
preloadImage = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url; // 重复设置src确保加载
});
}
/**
* 预加载单个音频
* @param url - 音频的URL地址
* @returns {Promise<Audio>} 加载完成的Audio对象Promise
*/
preloadAudio = (url) => {
return new Promise((resolve, reject) => {
const audio = new Audio();
// 当音频可以播放时解析Promise
audio.oncanplay = a => {
resolve(audio);
};
// 加载出错时拒绝Promise
audio.onerror = () => {
reject();
};
audio.src = url;
audio.load();
});
}
// 缓存页面元素
cartoonElementsBuffer = {}
/**
* 创建动画元素并缓存
* @param key - 元素的唯一标识符
* @param type - 元素类型,可选值:"MySprite", "ShapeRect", "ShapeRectNew", "Label"
* @param width - 元素宽度
* @param heigth - 元素高度
* @param initX - 初始X坐标
* @param initY - 初始Y坐标
* @returns {Object} 创建的元素对象
*/
createCartoonElement = (key, type, width?:number, heigth?:number, initX?:number, initY?:number)=>{
// 初始化元素对象
this.cartoonElementsBuffer[key] = {}
this.cartoonElementsBuffer[key].id = key;
this.cartoonElementsBuffer[key].width = width;
this.cartoonElementsBuffer[key].heigth = heigth;
this.cartoonElementsBuffer[key].width = width;
this.cartoonElementsBuffer[key].heigth = heigth;
// 设置初始位置
this.cartoonElementsBuffer[key].x = initX;
this.cartoonElementsBuffer[key].y = initY;
// 根据类型创建不同的元素
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;
default : this.cartoonElementsBuffer[key].ref = new MySprite(); break;
}
// 设置元素位置
this.cartoonElementsBuffer[key].ref.x = initX;
this.cartoonElementsBuffer[key].ref.y = initY;
// 为元素创建动画控制器
this.cartoonElementsBuffer[key].animation = new CartoonAnimation(this.cartoonElementsBuffer[key].ref)
return this.cartoonElementsBuffer[key]
}
/**
* 创建元素但不缓存
* 用于创建临时使用的元素
* @param type - 元素类型,可选值:"MySprite", "ShapeRect"
* @param initX - 初始X坐标
* @param initY - 初始Y坐标
* @returns {Object} 创建的元素对象
*/
createElement = (type, initX?:number, initY?:number)=>{
let element;
// 根据类型创建不同的元素
switch(type){
case "MySprite": element = new MySprite(); break;
case "ShapeRect": element = new ShapeRect(); break;
default : element = new MySprite(); break;
}
// 设置元素位置
element.x = initX;
element.y = initY;
return element
}
/**
* 创建文本标签元素但不缓存
* @param {Object} config - 标签配置对象
* @param {string} config.text - 文本内容
* @param {string} config.fontName - 字体名称
* @param {string} config.fontColor - 字体颜色
* @param {number} config.fontSize - 字体大小
* @param {string} config.textAlign - 文本对齐方式
* @param {number} initX - 初始X坐标
* @param {number} initY - 初始Y坐标
* @returns {Label} 创建的标签对象
*/
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
}
/**
* 获取缓存元素的引用
* @param key - 元素的唯一标识符
* @returns {Object|undefined} 元素引用或undefined(如果元素不存在)
*/
getCartoonElementRef = (key)=>{
if(this.cartoonElementsBuffer[key]){
return this.cartoonElementsBuffer[key].ref;
}else{
return undefined
}
}
/**
* 获取缓存的元素对象
* @param key - 元素的唯一标识符
* @returns {Object|undefined} 元素对象或undefined
*/
getCartoonElement = (key)=>{
return this.cartoonElementsBuffer[key]
}
/**
* 设置缓存元素的位置
* @param key - 元素的唯一标识符
* @param posi - 位置对象,包含x和y属性
*/
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
}
/**
* 设置缓存元素的X坐标
* @param key - 元素的唯一标识符
* @param x - X坐标值
*/
setCartoonElementPositionX = (key, x)=>{
this.cartoonElementsBuffer[key].ref.x = x
this.cartoonElementsBuffer[key].x = x
}
/**
* 设置缓存元素的相对X坐标
* @param key - 元素的唯一标识符
* @param x - 相对X坐标值
*/
setCartoonElementRelativePositionX = (key, x)=>{
this.cartoonElementsBuffer[key].relativeX = x
}
/**
* 设置缓存元素的Y坐标
* @param key - 元素的唯一标识符
* @param y - Y坐标值
*/
setCartoonElementPositionY = (key, y)=>{
this.cartoonElementsBuffer[key].ref.y = y
this.cartoonElementsBuffer[key].y = y
}
/**
* 设置缓存元素的相对Y坐标
* @param key - 元素的唯一标识符
* @param y - 相对Y坐标值
*/
setCartoonElementRelativePositionY = (key, y)=>{
this.cartoonElementsBuffer[key].relativeY = y
}
/**
* 获取缓存元素的位置
* @param key - 元素的唯一标识符
* @returns {{x: number, y: number}} 位置对象
*/
getCartoonElementPosition = (key)=>{
return {
x: this.cartoonElementsBuffer[key].x,
y: this.cartoonElementsBuffer[key].y
}
}
/**
* 获取缓存元素的相对位置
* @param key - 元素的唯一标识符
* @returns {{x: number, y: number}} 相对位置对象
*/
getCartoonElementRelativePosition = (key)=>{
return {
x: this.cartoonElementsBuffer[key].relativeX,
y: this.cartoonElementsBuffer[key].relativeY
}
}
/**
* 全局动画控制器
* 用于控制整个Cartoon实例的动画
*/
animation = new CartoonAnimation(this)
}
import {
MySprite,
getMinScale,
ShapeRect,
tweenChange,
randomSortByArr,
Label,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem
} from "./Unit";
/**
* CartoonAnimation 类
* 用于管理和控制单个元素的动画效果
* 提供动画注册、移动、缩放和翻转等功能
*/
export class CartoonAnimation {
/**
* 存储注册的动画函数
* 键为动画名称,值为动画函数
*/
animations = {}
/**
* 当前操作的元素引用
*/
currentRef;
/**
* 构造函数
* @param ref - 要控制的元素引用
*/
constructor(ref){
this.currentRef = ref
}
/**
* 添加自定义动画
* @param key - 动画的唯一标识符
* @param func - 动画执行函数
*/
add(key:string, func:Function){
this.animations[key] = func
}
/**
* 移动元素到指定位置
* @param ele - 要移动的元素
* @param distPosition - 目标位置对象,包含x、y等属性
* @param runTime - 动画运行时间(秒)
* @param callback - 动画完成后的回调函数
*/
move = (ele, distPosition, runTime, callback?:Function )=>{
tweenChange(ele, distPosition, runTime, ()=>{
callback && callback()
});
}
/**
* 改变元素的缩放
* 实际上是move方法的别名,用于改变scaleX、scaleY等属性
*/
scaleChange = this.move;
/**
* 运行指定名称的动画
* @param key - 要运行的动画名称
*/
run( key:string ){
this.animations[key]()
}
/**
* 卡片翻转动画
* 通过缩放X轴实现卡片翻转效果,在中间点切换正反面显示
* @param callback - 动画完成后的回调函数
*/
overCard = function (callback?: any){
// 保存当前X轴缩放值
let w = this.currentRef.scaleX;
// 第一阶段:将X轴缩放到0(卡片变成一条线)
this.scaleChange(this.currentRef, { scaleX: 0 }, 0.3, () => {
// 在最薄处切换正反面显示状态
this.currentRef.frontSide.visible = !this.currentRef.frontSide.visible;
this.currentRef.backSide.visible = !this.currentRef.backSide.visible;
// 第二阶段:恢复到原始宽度,显示另一面
this.scaleChange(this.currentRef, { scaleX: w }, 0.3, () => {
// 动画完成后执行回调
callback && callback();
});
});
}
}
\ No newline at end of file
import TWEEN from '@tweenjs/tween.js';
interface AirWindow extends Window {
air: any;
curCtx: any;
curImages: any;
}
declare let window: AirWindow;
/**
* Unit.ts - 游戏精灵和图形渲染相关类库
* 包含基础精灵类、文本标签、形状、动画等组件
*/
import TWEEN from "@tweenjs/tween.js"; // 导入补间动画库
import { del } from "selenium-webdriver/http";
import construct = Reflect.construct;
/**
* 基础精灵类
* 提供基本的位置、绘制和更新功能
*/
class Sprite {
x = 0;
y = 0;
color = '';
radius = 0;
alive = false;
margin = 0;
angle = 0;
ctx;
x = 0; // X坐标
y = 0; // Y坐标
color = ""; // 颜色
radius = 0; // 半径
alive = false; // 存活状态
margin = 0; // 边距
angle = 0; // 角度
ctx; // Canvas上下文
id; // 唯一标识
/**
* 构造函数
* @param ctx - Canvas上下文,如果为空则使用全局上下文
*/
constructor(ctx = null) {
if (!ctx) {
this.ctx = window.curCtx;
this.ctx = window["curCtx"];
} else {
this.ctx = ctx;
}
}
/**
* 更新精灵状态
* @param $event - 事件对象
*/
update($event) {
this.draw();
}
draw() {
}
/**
* 绘制精灵(基类中为空实现)
*/
draw() {}
}
/**
* 扩展精灵类
* 提供更多功能,如尺寸、锚点、缩放、旋转、透明度和子节点管理
*/
export class MySprite extends Sprite {
_width = 0;
_height = 0;
_anchorX = 0;
_anchorY = 0;
_offX = 0;
_offY = 0;
scaleX = 1;
scaleY = 1;
_alpha = 1;
rotation = 0;
visible = true;
skewX = 0;
skewY = 0;
_shadowFlag = false;
_shadowColor;
_shadowOffsetX = 0;
_shadowOffsetY = 0;
_shadowBlur = 5;
_radius = 0;
children = [this];
childDepandVisible = true;
childDepandAlpha = false;
img;
_z = 0;
_showRect;
_bitmapFlag = false;
_offCanvas;
_offCtx;
isCircleStyle = false; // 切成圆形
parent;
_maskSpr;
_width = 0; // 宽度
_height = 0; // 高度
_anchorX = 0; // X轴锚点(0-1)
_anchorY = 0; // Y轴锚点(0-1)
_offX = 0; // X轴偏移量
_offY = 0; // Y轴偏移量
scaleX = 1; // X轴缩放
scaleY = 1; // Y轴缩放
_alpha = 1; // 透明度
rotation = 0; // 旋转角度
visible = true; // 可见性
skewX = 0; // X轴倾斜
skewY = 0; // Y轴倾斜
children = [this]; // 子节点数组,默认包含自身
childDepandVisible = true; // 子节点是否继承可见性
childDepandAlpha = false; // 子节点是否继承透明度
img; // 图像对象
_z = 0; // Z轴顺序(用于排序)
/**
* 初始化精灵
* @param imgObj - 图像对象
* @param anchorX - X轴锚点,默认为0.5(中心点)
* @param anchorY - Y轴锚点,默认为0.5(中心点)
*/
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;
}
setShowRect(rect) {
this._showRect = rect;
}
setShadow(offX, offY, blur, color = 'rgba(0, 0, 0, 0.3)') {
this._shadowFlag = true;
this._shadowColor = color;
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
this._shadowBlur = blur;
}
setRadius(r) {
this._radius = r;
}
setMaskSpr(spr) {
this._maskSpr = spr;
this._createOffCtx();
}
_createOffCtx() {
if (!this._offCtx) {
this._offCanvas = document.createElement('canvas'); // 创建一个新的canvas
this.width = this._offCanvas.width = this.width; // 创建一个正好包裹住一个粒子canvas
this.height = this._offCanvas.height = this.height;
this._offCtx = this._offCanvas.getContext('2d');
}
}
/**
* 更新精灵状态
* @param $event - 事件对象
*/
update($event = null) {
if (!this.visible && this.childDepandVisible) {
return;
return; // 如果不可见且子节点继承可见性,则不更新
}
this.draw();
}
draw() {
/**
* 绘制精灵
* 保存上下文 -> 初始化绘制环境 -> 更新子节点 -> 恢复上下文
*/
draw() {
this.ctx.save();
this.drawInit();
......@@ -145,138 +117,78 @@ export class MySprite extends Sprite {
this.updateChildren();
this.ctx.restore();
}
/**
* 初始化绘制环境
* 设置位置、旋转、缩放、透明度和变换
*/
drawInit() {
this.ctx.translate(this.x, this.y); // 设置位置
this.ctx.translate(this.x, this.y);
this.ctx.rotate(this.rotation * Math.PI / 180);
this.ctx.scale(this.scaleX, this.scaleY);
this.ctx.globalAlpha = this.alpha;
this.ctx.rotate((this.rotation * Math.PI) / 180); // 设置旋转(角度转弧度)
this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0);
this.ctx.scale(this.scaleX, this.scaleY); // 设置缩放
this.ctx.globalAlpha = this.alpha; // 设置透明度
this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0); // 设置倾斜变换
}
/**
* 绘制自身
* 如果有图像,则绘制图像
*/
drawSelf() {
if (this._shadowFlag) {
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
this.ctx.shadowBlur = this._shadowBlur;
this.ctx.shadowColor = this._shadowColor;
} else {
this.ctx.shadowOffsetX = 0;
this.ctx.shadowOffsetY = 0;
this.ctx.shadowBlur = null;
this.ctx.shadowColor = null;
}
if (this._radius) {
const r = this._radius;
const w = this.width;
const h = this.height;
this.ctx.beginPath()
this._roundRect(-w / 2, - h / 2, w, h, r * 1 || 0);
this.ctx.clip();
}
if (this.isCircleStyle) {
this.ctx.beginPath()
this.ctx.arc(0, 0, Math.max(this.width, this.height) / 2, 0, Math.PI * 2, false); // 圆形
this.ctx.clip();
}
if (this.img) {
if (this._showRect) {
const rect = this._showRect;
this.ctx.drawImage(this.img, rect.x, rect.y, rect.width, rect.height, this._offX + rect.x, this._offY + rect.y, rect.width, rect.height);
} else {
if (this._offCtx) {
this._offScreenRender();
} else {
this.ctx.drawImage(this.img, this._offX, this._offY);
}
}
}
}
_offScreenRender() {
this._offCtx.save();
this._offCtx.clearRect(0, 0, this.width, this.height);
this._offCtx.drawImage(this.img, 0, 0);
if (this._maskSpr) {
this._offCtx.globalCompositeOperation = 'destination-in';
this._offCtx.drawImage(this._maskSpr.img, this._maskSpr.x + this._maskSpr._offX - this._offX , this._maskSpr.y + this._maskSpr._offY - this._offY);
}
this.ctx.drawImage(this._offCanvas, this._offX, this._offY);
this._offCtx.restore();
}
_roundRect(x, y, w, h, r) {
const min_size = Math.min(w, h);
if (r > min_size / 2) r = min_size / 2;
// 开始绘制
const ctx = this.ctx;
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
/**
* 更新所有子节点
* 遍历子节点数组,绘制自身或更新子节点
*/
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();
this.drawSelf(); // 绘制自身
}
} else {
child.update();
this.children[i].update(); // 更新子节点
}
}
}
/**
* 加载图像
* @param url - 图像URL
* @param anchorX - X轴锚点
* @param anchorY - Y轴锚点
* @returns Promise对象,加载完成后初始化精灵
*/
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;
});
}
/**
* 添加子节点
* @param child - 子节点
* @param z - Z轴顺序,用于排序
*/
addChild(child, z = 1) {
if (this.children.indexOf(child) === -1) {
this.children.push(child);
......@@ -284,16 +196,20 @@ export class MySprite extends Sprite {
child.parent = this;
}
// 根据z值排序子节点
this.children.sort((a, b) => {
return a._z - b._z;
});
// 如果设置了子节点继承透明度,则设置子节点透明度
if (this.childDepandAlpha) {
child.alpha = this.alpha;
}
}
/**
* 移除子节点
* @param child - 要移除的子节点
*/
removeChild(child) {
const index = this.children.indexOf(child);
if (index !== -1) {
......@@ -301,32 +217,35 @@ 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--; // 调整索引,因为数组长度减少了
}
}
}
}
/**
* 改变所有子节点的透明度
* @param alpha - 透明度值
*/
_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;
}
}
}
set bitmapFlag(v) {
this._bitmapFlag = v;
}
get bitmapFlag() {
return this._bitmapFlag;
}
/**
* 设置透明度,如果设置了子节点继承透明度,则同时设置子节点透明度
*/
set alpha(v) {
this._alpha = v;
if (this.childDepandAlpha) {
......@@ -336,6 +255,10 @@ export class MySprite extends Sprite {
get alpha() {
return this._alpha;
}
/**
* 设置宽度,同时刷新锚点偏移
*/
set width(v) {
this._width = v;
this.refreshAnchorOff();
......@@ -343,6 +266,10 @@ export class MySprite extends Sprite {
get width() {
return this._width;
}
/**
* 设置高度,同时刷新锚点偏移
*/
set height(v) {
this._height = v;
this.refreshAnchorOff();
......@@ -350,6 +277,10 @@ export class MySprite extends Sprite {
get height() {
return this._height;
}
/**
* 设置X轴锚点,同时刷新锚点偏移
*/
set anchorX(value) {
this._anchorX = value;
this.refreshAnchorOff();
......@@ -357,6 +288,10 @@ export class MySprite extends Sprite {
get anchorX() {
return this._anchorX;
}
/**
* 设置Y轴锚点,同时刷新锚点偏移
*/
set anchorY(value) {
this._anchorY = value;
this.refreshAnchorOff();
......@@ -364,19 +299,32 @@ export class MySprite extends Sprite {
get anchorY() {
return this._anchorY;
}
/**
* 刷新锚点偏移
* 根据宽高和锚点计算偏移量
*/
refreshAnchorOff() {
this._offX = -this._width * this.anchorX;
this._offY = -this._height * this.anchorY;
}
/**
* 同时设置X和Y轴的缩放值
* @param value - 缩放值
*/
setScaleXY(value) {
this.scaleX = this.scaleY = value;
}
/**
* 获取精灵的包围盒
* 考虑父节点的位置和缩放
* @returns 包含x、y、width、height的对象
*/
getBoundingBox() {
const getParentData = (item) => {
// 递归获取所有父节点的位置和缩放信息
const getParentData = item => {
let px = item.x;
let py = item.y;
......@@ -384,7 +332,6 @@ export class MySprite extends Sprite {
let sy = item.scaleY;
const parent = item.parent;
if (parent) {
const obj = getParentData(parent);
const _x = obj.px;
......@@ -392,150 +339,167 @@ export class MySprite extends Sprite {
const _sx = obj.sx;
const _sy = obj.sy;
// 计算考虑父节点缩放后的位置
px = _x + item.x * _sx;
py = _y + item.y * _sy;
// 累积缩放值
sx *= _sx;
sy *= _sy;
}
return {px, py, sx, sy};
return { px, py, sx, sy };
};
const data = getParentData(this);
// 计算最终的包围盒
const x = data.px + this._offX * Math.abs(data.sx);
const y = data.py + this._offY * Math.abs(data.sy);
const width = this.width * Math.abs(data.sx);
const height = this.height * Math.abs(data.sy);
return {x, y, width, height};
}
// 不考虑父节点的简单计算方式(已注释)
// const x = this.x + this._offX * Math.abs(this.scaleX);
// const y = this.y + this._offY * Math.abs(this.scaleY);
// const width = this.width * Math.abs(this.scaleX);
// const height = this.height * Math.abs(this.scaleY);
return { x, y, width, height };
}
}
/**
* 颜色精灵类
* 继承自MySprite,可以将图像渲染为指定的RGB颜色
*/
export class ColorSpr extends MySprite {
r = 0;
g = 0;
b = 0;
r = 0; // 红色分量
g = 0; // 绿色分量
b = 0; // 蓝色分量
/**
* 创建颜色处理的Canvas
* 将图像的每个像素的RGB值替换为指定的颜色值
*/
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];
// 保留原透明度,替换RGB值
c.data[x] = this.r;
c.data[x + 1] = this.g;
c.data[x + 2] = this.b;
// 灰度处理的替代方案(已注释)
// c.data[x] = c.data[x + 1] = c.data[x + 2] = (r + g + b) / 3 ;
// // c.data[x + 3] = 255;
}
}
// 将处理后的图像数据放回Canvas
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
}
/**
* 绘制自身
* 先调用父类的绘制方法,再应用颜色处理
*/
drawSelf() {
super.drawSelf();
this.createGSCanvas();
}
}
/**
* 灰度精灵类
* 继承自MySprite,可以将图像渲染为灰度效果
*/
export class GrayscaleSpr extends MySprite {
grayScale = 120; // 灰度值,范围0-255
grayScale = 120;
/**
* 创建灰度处理的Canvas
* 将图像的每个像素转换为指定的灰度值
*/
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];
// const a = c.data[x + 3];
// const a = c.data[x + 3]; // 透明度
c.data[x] = c.data[x + 1] = c.data[x + 2] = this.grayScale; // (r + g + b) / 3;
// c.data[x + 3] = 255;
// 将RGB三个通道都设置为相同的灰度值
c.data[x] = c.data[x + 1] = c.data[x + 2] = this.grayScale; // 也可以用: (r + g + b) / 3;
// c.data[x + 3] = 255; // 可以设置透明度
}
}
// 将处理后的图像数据放回Canvas
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;
labelArr; // 标签数组
baseUrl; // 基础URL
/**
* 设置文本内容
* @param data - 字符到图像的映射对象
* @param text - 要显示的文本
*/
setText(data, text) {
this.labelArr = [];
const labelArr = [];
const tmpArr = text.split('');
let totalW = 0;
let h = 0;
for (const tmp of tmpArr) {
const tmpArr = text.split(""); // 将文本分割为单个字符
let totalW = 0; // 总宽度
let h = 0; // 高度
// 为每个字符创建一个精灵
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);
......@@ -543,142 +507,168 @@ 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;
// 排列字符精灵
let offX = -totalW / 2; // 从左侧开始,居中对齐
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;
// fontSize:String = '40px';
fontName = 'Verdana';
textAlign = 'left';
fontSize = 40;
fontColor = '#000000';
fontWeight = 900;
_maxWidth;
outline = 0;
outlineColor = '#ffffff';
// _shadowFlag = false;
// _shadowColor;
// _shadowOffsetX;
// _shadowOffsetY;
// _shadowBlur;
_outlineFlag = false;
_outLineWidth;
_outLineColor;
text: String; // 文本内容
// fontSize:String = '40px'; // 字体大小(字符串形式,已注释)
fontName: String = "Verdana"; // 字体名称
textAlign: String = "left"; // 文本对齐方式
fontSize = 40; // 字体大小(数字形式)
fontColor = "#000000"; // 字体颜色
fontWeight = 900; // 字体粗细
maxWidth; // 最大宽度
outline = 0; // 轮廓宽度
outlineColor = "#ffffff"; // 轮廓颜色
maxSingalLineWidth = 0; // 单行最大宽度,用于自动换行
_shadowFlag = false; // 是否启用阴影
_shadowColor; // 阴影颜色
_shadowOffsetX; // 阴影X偏移
_shadowOffsetY; // 阴影Y偏移
_shadowBlur; // 阴影模糊度
_outlineFlag = false; // 是否启用轮廓
_outLineWidth; // 轮廓宽度
_outLineColor; // 轮廓颜色
_warpLineY = 0; // 换行时的Y坐标偏移
/**
* 构造函数
* @param ctx - Canvas上下文
*/
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;
this._height = this.fontSize;
this.refreshAnchorOff();
this.ctx.restore();
}
/**
* 设置最大尺寸
* 如果文本宽度超过指定宽度,则按比例缩小
* @param w - 最大宽度
*/
setMaxSize(w) {
this._maxWidth = w;
this.maxWidth = w;
this.refreshSize();
if (this.width >= w) {
// 按比例缩放,保持宽高比
this.scaleX *= w / this.width;
this.scaleY *= w / this.width;
}
}
/**
* 显示标签,带淡入动画效果
* @param callBack - 动画完成后的回调函数
*/
show(callBack = null) {
this.visible = true;
if (this.alpha >= 1) {
return;
return; // 如果已经完全不透明,则不需要动画
}
// 创建透明度从当前值到1的补间动画
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(() => {
.to({ alpha: 1 }, 800) // 800毫秒内完成
// .easing(TWEEN.Easing.Quadratic.Out) // 使用缓动函数使动画更平滑(已注释)
.onComplete(function() {
if (callBack) {
callBack();
callBack(); // 动画完成后执行回调
}
})
.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;
// }
.start(); // 立即开始动画
}
setOutline(width = 5, color = '#ffffff') {
/**
* 设置文本阴影
* @param offX - X轴偏移,默认2
* @param offY - Y轴偏移,默认2
* @param blur - 模糊度,默认2
* @param color - 阴影颜色,默认半透明黑色
*/
setShadow(offX = 2, offY = 2, blur = 2, color = "rgba(0, 0, 0, 0.2)") {
this._shadowFlag = true;
this._shadowColor = color;
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
this._shadowBlur = blur;
}
/**
* 设置文本轮廓
* @param width - 轮廓宽度,默认5
* @param color - 轮廓颜色,默认白色
*/
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;
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) {
this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor;
......@@ -687,1165 +677,1541 @@ 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; // 增加Y坐标偏移,实现换行
}
else {
line = testLine; // 继续添加单词到当前行
}
}
this.y = -this._warpLineY /2 // 调整Y坐标,使文本垂直居中
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; // 线宽
/**
* 设置矩形尺寸和圆角
* @param w - 宽度
* @param h - 高度
* @param r - 圆角半径
*/
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
/**
* 设置矩形轮廓
* @param color - 描边颜色
* @param lineWidth - 线宽
*/
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
this.ctx.fillText(this.text, 0, 0);
/**
* 绘制圆角矩形形状
* 使用Canvas路径API绘制带圆角的矩形
*/
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;
textArr = []; // 文本分段数组
fontSize = 40; // 字体大小
/**
* 设置文本内容,并标记需要高亮的单词
* @param text - 原始文本内容
* @param words - 需要高亮的单词数组
*/
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}#`);
// newText = newText.replace(word, `#${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();
// 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;
}
// 设置富文本尺寸
this.width = curX;
this.height = this.fontSize;
this.refreshAnchorOff();
this.ctx.restore();
}
/**
* 显示富文本,带淡入动画效果
* @param callBack - 动画完成后的回调函数
*/
show(callBack = null) {
// console.log(' in show ');
this.visible = true;
// this.alpha = 0;
// this.alpha = 0; // 已注释
// 创建透明度从当前值到1的补间动画
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(() => {
.to({ alpha: 1 }, 800) // 800毫秒内完成
// .easing(TWEEN.Easing.Quadratic.Out) // 使用缓动函数使动画更平滑(已注释)
.onComplete(function() {
if (callBack) {
callBack();
callBack(); // 动画完成后执行回调
}
})
.start(); // Start the tween immediately.
.start(); // 立即开始动画
}
/**
* 绘制富文本内容
* 根据文本分段数组绘制文本,奇偶段落使用不同颜色
*/
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.strokeText(this.text, 0, 0);
this.ctx.fillStyle = '#000000';
// this.ctx.fillText(this.text, 0, 0);
this.ctx.strokeStyle = "#ffffff";
// this.ctx.strokeText(this.text, 0, 0); // 已注释
// 设置默认填充样式(未使用)
this.ctx.fillStyle = "#000000";
// this.ctx.fillText(this.text, 0, 0); // 已注释
// 逐段绘制文本,使用不同颜色
let curX = 0;
for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width;
if ((i + 1) % 2 === 0) {
this.ctx.fillStyle = '#c8171e';
// 奇数索引(偶数段落)使用红色,偶数索引(奇数段落)使用黑色
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;
curX += w; // 更新X坐标位置
}
}
}
/**
* 富文本类
* 用于显示带有自动换行功能的文本
*/
export class RichText extends Label {
disH = 30; // 行间距
disH = 30;
offW = 10;
constructor(ctx?: any) {
/**
* 构造函数
* @param ctx - Canvas上下文
*/
constructor(ctx) {
super(ctx);
// this.dataArr = dataArr;
// this.dataArr = dataArr; // 已注释
}
/**
* 绘制富文本内容
* 实现自动换行和多行文本绘制
*/
drawText() {
if (!this.text) {
return;
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 row = [];
const w = selfW - this.offW * 2;
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;
// 按空格分割单词
const chr = this.text.split(" ");
let temp = "";
const row = []; // 存储每一行的文本
const w = selfW - 80; // 有效宽度(留出边距)
const disH = (this.fontSize + this.disH) * this.scaleY; // 行高(考虑缩放)
// 自动换行处理
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);
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坐标间隔disH
}
// this.ctx.strokeText(this.text, 0, 0);
// 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
// this.ctx.fillStyle = '#ff7600'; // 已注释
// 绘制每一行文本
for (let b = 0; b < row.length; b++) {
this.ctx.fillText(row[b], x, y + (b + 1) * disH); // 每行字体y坐标间隔disH
}
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class LineRect extends MySprite {
lineColor = '#ffffff';
lineWidth = 10;
setSize(w, h) {
this.width = w;
this.height = h;
}
drawLine() {
this.ctx.beginPath();
this.ctx.moveTo(this._offX, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY + this.height);
this.ctx.lineTo(this._offX, this._offY + this.height);
this.ctx.closePath();
this.ctx.lineWidth = this.lineWidth;
// this.ctx.fillStyle = "rgb(2,33,42)"; //指定填充颜色
// this.ctx.fill(); //对多边形进行填充
this.ctx.strokeStyle = this.lineColor; // "#ffffff";
this.ctx.stroke();
}
drawSelf() {
super.drawSelf();
this.drawLine();
}
}
export class ShapeRect extends MySprite {
fillColor = '#FF0000';
setSize(w, h) {
this.width = w;
this.height = h;
// console.log('w:', w);
// console.log('h:', h);
}
drawShape() {
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';
radius = 0;
}
}
/**
* 矩形形状类
* 用于绘制简单的矩形,支持填充颜色
*/
export class ShapeRect extends MySprite {
fillColor = "#FF0000"; // 填充颜色,默认红色
setRadius(r) {
this.anchorX = this.anchorY = 0.5;
/**
* 设置矩形尺寸
* @param w - 宽度
* @param h - 高度
*/
setSize(w, h) {
this.width = w;
this.height = h;
this.radius = r;
this.width = r * 2;
this.height = r * 2;
// console.log('w:', w); // 已注释
// console.log('h:', h); // 已注释
}
/**
* 绘制矩形形状
* 使用Canvas fillRect方法绘制矩形
*/
drawShape() {
this.ctx.beginPath();
this.ctx.fillStyle = this.fillColor;
this.ctx.arc(0, 0, this.radius, 0, angleToRadian(360));
this.ctx.fill();
this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
}
/**
* 绘制自身
* 调用父类绘制方法,然后绘制矩形形状
*/
/**
* 绘制自身
* 调用父类绘制方法,然后绘制圆形形状
*/
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;
/**
* 圆形形状类
* 用于绘制圆形或圆弧,支持填充和描边
*/
export class ShapeCircle extends MySprite {
fillColor = "#FF0000"; // 填充颜色,默认红色
radius = 0; // 圆半径
startRadian = 0; // 起始弧度
endRadian = 180; // 结束弧度
strokeLineWidth = 5; // 描边线宽
strokeColor = "#702dee"; // 描边颜色
drawType = "fill" // 绘制类型:fill-填充,stroke-描边
counterclockwise = false; // false 逆时针 true 顺时针
/**
* 设置圆半径
* @param r - 半径值
*/
setRadius(r) {
this.anchorX = this.anchorY = 0.5; // 设置锚点为中心
this.radius = r;
this.width = r * 2; // 设置宽度为直径
this.height = r * 2; // 设置高度为直径
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
/**
* 绘制圆形或圆弧
* 根据drawType属性决定是填充还是描边
*/
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 + this._offX, height - radius + this._offY, radius, 0, Math.PI / 2);
// 矩形下边线
ctx.lineTo(radius + this._offX, height + this._offY);
// 左下角圆弧,弧度从1/2PI到PI
ctx.arc(radius + this._offX, height - radius + this._offY, radius, Math.PI / 2, Math.PI);
// 矩形左边线
ctx.lineTo(0 + this._offX, radius + this._offY);
// 左上角圆弧,弧度从PI到3/2PI
ctx.arc(radius + this._offX, radius + this._offY, radius, Math.PI, Math.PI * 3 / 2);
// 上边线
ctx.lineTo(width - radius + this._offX, 0 + this._offY);
// 右上角圆弧
ctx.arc(width - radius + this._offX, radius + this._offY, radius, Math.PI * 3 / 2, Math.PI * 2);
// 右边线
ctx.lineTo(width + this._offX, height - radius + this._offY);
ctx.closePath();
if (this.fill) {
ctx.fillStyle = this.fillColor;
ctx.fill();
}
if (this.stroke) {
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.strokeColor;
ctx.stroke();
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.fillColor = this.fillColor;
this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian);
this.ctx.fill();
break;
}
ctx.restore();
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class MyAnimation extends MySprite {
frameArr = [];
frameIndex = 0;
playFlag = false;
lastDateTime;
curDelay = 0;
loop = false;
playEndFunc;
delayPerUnit = 0.07;
restartFlag = false;
reverseFlag = false;
/**
* 动画精灵类
* 用于创建和播放帧动画,支持循环、反转等功能
*/
export class MyAnimation extends MySprite {
frameArr = []; // 帧数组,存储所有动画帧
frameIndex = 0; // 当前帧索引
playFlag = false; // 播放标志
lastDateTime; // 上次更新时间
curDelay = 0; // 当前延迟时间
loop = false; // 是否循环播放
playEndFunc; // 播放结束回调函数
delayPerUnit = 1; // 每帧延迟时间
restartFlag = false; // 重新开始标志
reverseFlag = false; // 反向播放标志
/**
* 通过图像对象添加动画帧
* @param img - 图像对象
*/
addFrameByImg(img) {
const spr = new MySprite(this.ctx);
spr.init(img);
this._refreshSize(img);
spr.visible = false;
spr.visible = false; // 初始设为不可见
this.addChild(spr);
this.frameArr.push(spr);
// 确保当前帧可见
this.frameArr[this.frameIndex].visible = true;
}
/**
* 通过图像URL添加动画帧
* @param url - 图像URL地址
*/
addFrameByUrl(url) {
const spr = new MySprite(this.ctx);
// 异步加载图像
spr.load(url).then(img => {
this._refreshSize(img);
});
spr.visible = false;
spr.visible = false; // 初始设为不可见
this.addChild(spr);
this.frameArr.push(spr);
// 确保当前帧可见
this.frameArr[this.frameIndex].visible = true;
}
_refreshSize(img: any) {
if (this.width < img.width) {
this.width = img.width;
/**
* 刷新动画尺寸
* 根据帧图像调整动画精灵的尺寸,确保能完全显示所有帧
* @param img - 图像对象
* @private
*/
_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();
this.lastDateTime = new Date().getTime(); // 记录开始时间
}
/**
* 停止播放动画
*/
stop() {
this.playFlag = false;
}
/**
* 重新播放动画
* 设置重新开始标志并开始播放
*/
replay() {
this.restartFlag = true;
this.play();
}
/**
* 反转动画播放顺序
* 切换反向播放标志,反转帧数组,并重置帧索引
*/
reverse() {
this.reverseFlag = !this.reverseFlag;
this.frameArr.reverse();
this.frameIndex = 0;
this.frameArr.reverse(); // 反转帧数组
this.frameIndex = 0; // 重置帧索引
}
/**
* 显示所有帧
* 将所有帧的透明度设为1(完全不透明)
*/
showAllFrame() {
for (const frame of this.frameArr ) {
frame.alpha = 1;
for (let i = 0; i < this.frameArr.length; i++) {
this.frameArr[i].alpha = 1;
}
}
/**
* 隐藏所有帧
* 将所有帧的透明度设为0(完全透明)
*/
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;
// 确保当前帧可见
this.frameArr[this.frameIndex].visible = true;
// 执行结束回调(如果有)
if (this.playEndFunc) {
const func = this.playEndFunc;
this.playEndFunc();
this.playEndFunc = null;
func();
}
}
/**
* 更新动画帧
* 隐藏当前帧,显示下一帧,处理循环和结束逻辑
*/
updateFrame() {
// 隐藏当前帧
if (this.frameArr[this.frameIndex]) {
this.frameArr[this.frameIndex].visible = false;
}
this.frameIndex ++;
// 移动到下一帧
this.frameIndex++;
if (this.frameIndex >= this.frameArr.length) {
// 到达最后一帧,处理循环逻辑
if (this.loop) {
// 循环模式,回到第一帧
this.frameIndex = 0;
} else if (this.restartFlag) {
// 重新开始模式,重置标志并回到第一帧
this.restartFlag = false;
this.frameIndex = 0;
} else {
this.frameIndex -- ;
// 非循环模式,保持在最后一帧并结束播放
this.frameIndex--;
this.playEnd();
return;
}
}
// 显示新的当前帧
this.frameArr[this.frameIndex].visible = true;
}
/**
* 更新延迟时间并在达到帧间隔时更新帧
* @param delay - 增加的延迟时间(秒)
* @private
*/
_updateDelay(delay) {
this.curDelay += delay;
// 如果累计延迟未达到每帧延迟时间,则不更新
if (this.curDelay < this.delayPerUnit) {
return;
}
// 减去一个帧间隔的延迟时间,保留剩余延迟
this.curDelay -= this.delayPerUnit;
// 更新到下一帧
this.updateFrame();
}
/**
* 更新上次时间并计算延迟
* 计算自上次更新以来经过的时间,并更新延迟
* @private
*/
_updateLastDate() {
if (!this.playFlag) { return; }
if (!this.playFlag) {
return; // 如果未播放则不更新
}
let delay = 0;
if (this.lastDateTime) {
// 计算自上次更新以来经过的时间(秒)
delay = (new Date().getTime() - this.lastDateTime) / 1000;
}
// 更新上次时间为当前时间
this.lastDateTime = new Date().getTime();
// 更新延迟
this._updateDelay(delay);
}
/**
* 更新动画
* 调用父类更新方法,然后更新动画时间
* @param $event - 更新事件参数
*/
update($event: any = null) {
super.update($event);
this._updateLastDate();
}
}
// --------=========== util func =============-------------
export function tweenChange(item, obj, time = 0.8, callBack = null, easing = null, update = null) {
const tween = createTween(item, obj, time, callBack, easing, update)
tween.start();
return tween;
}
export function createTween(item, obj, time = 0.8, callBack = null, easing = null, update = null) {
// --------=========== 工具函数 =============-------------
/**
* 创建属性变化的补间动画
* @param item - 要进行动画的对象
* @param obj - 目标属性值对象
* @param time - 动画持续时间(秒),默认0.8秒
* @param callBack - 动画完成回调函数
* @param easing - 缓动函数
* @param update - 更新回调函数
* @returns {Tween} - 创建的补间动画对象
*/
export function tweenChange(
item,
obj,
time = 0.8,
callBack = null,
easing = null,
update = null
) {
// 创建从当前值到目标值的补间动画
const tween = new TWEEN.Tween(item).to(obj, time * 1000);
// 设置完成回调
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
// 设置缓动函数
if (easing) {
tween.easing(easing);
}
// 设置更新回调
if (update) {
tween.onUpdate( (a, b) => {
tween.onUpdate((a, b) => {
update(a, b);
});
}
return tween;
}
export function tweenQueue(arr) {
const showOneTween = () => {
const tween = arr.shift();
if (arr.length > 0) {
tween.onComplete( () => {
showOneTween();
});
}
// 开始动画
tween.start();
};
showOneTween();
return tween;
}
export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = null, loop = false) {
/**
* 创建旋转动画
* @param item - 要旋转的对象
* @param rotation - 目标旋转角度
* @param time - 动画持续时间(秒),默认0.8秒
* @param callBack - 动画完成回调函数
* @param easing - 缓动函数
*/
export function rotateItem(
item,
rotation,
time = 0.8,
callBack = null,
easing = null
) {
// 创建旋转补间动画
const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000);
// 设置完成回调
if (callBack) {
tween.onComplete(() => {
callBack();
});
} else if (loop) {
const speed = (rotation - item.rotation) / time;
tween.onComplete(() => {
item.rotation %= 360;
rotateItem(item, item.rotation + speed * time, time, null, easing, true);
});
}
// 设置缓动函数
if (easing) {
tween.easing(easing);
}
// 开始动画
tween.start();
}
export function scaleItem(item, scale, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ scaleX: scale, scaleY: scale}, time * 1000);
/**
* 创建缩放动画
* @param item - 要缩放的对象
* @param scale - 目标缩放比例
* @param time - 动画持续时间(秒),默认0.8秒
* @param callBack - 动画完成回调函数
* @param easing - 缓动函数
*/
export function scaleItem(
item,
scale,
time = 0.8,
callBack = null,
easing = null
) {
// 创建缩放补间动画(X和Y方向同时缩放)
const tween = new TWEEN.Tween(item).to(
{ scaleX: scale, scaleY: scale },
time * 1000
);
// 设置完成回调
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
// 设置缓动函数
if (easing) {
tween.easing(easing);
}
// 开始动画
tween.start();
return tween;
}
export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ x, y}, time * 1000);
/**
* 创建移动动画
* @param item - 要移动的对象
* @param x - 目标X坐标
* @param y - 目标Y坐标
* @param time - 动画持续时间(秒),默认0.8秒
* @param callBack - 动画完成回调函数
* @param easing - 缓动函数
* @returns {Tween} - 创建的补间动画对象
*/
export function moveItem(
item,
x,
y,
time = 0.8,
callBack = null,
easing = null
) {
// 创建移动补间动画
const tween = new TWEEN.Tween(item).to({ x, y }, time * 1000);
// 设置完成回调
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
// 设置缓动函数
if (easing) {
tween.easing(easing);
}
// 开始动画
tween.start();
return tween;
}
/**
* 创建弹性显示动画
* 从透明缩放为0的状态弹性显示到指定大小
* @param item - 要显示的对象
* @param s - 目标缩放比例,默认为1
*/
export function endShow(item, s = 1) {
// 初始状态:缩放为0且完全透明
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(() => {
})
.easing(TWEEN.Easing.Elastic.Out) // 使用弹性缓动函数使动画更平滑
.onComplete(function() {})
.start();
}
/**
* 创建隐藏动画
* 通过透明度渐变隐藏对象
* @param item - 要隐藏的对象
* @param time - 动画持续时间(秒),默认0.8秒
* @param callBack - 动画完成回调函数
* @param easing - 缓动函数
*/
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)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.to({ alpha: 0 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // 使用缓动函数使动画更平滑
.onComplete(function() {
// 动画完成后执行回调
if (callBack) {
callBack();
}
});
// 设置缓动函数
if (easing) {
tween.easing(easing);
}
// 开始动画
tween.start();
}
/**
* 创建显示动画
* 通过透明度渐变显示对象
* @param item - 要显示的对象
* @param time - 动画持续时间(秒),默认0.8秒
* @param callBack - 动画完成回调函数
* @param easing - 缓动函数
*/
export function showItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha === 1) {
// 如果已经完全不透明,则直接执行回调并返回
if (item.alpha == 1) {
if (callBack) {
callBack();
}
return;
}
// 确保对象可见
item.visible = true;
// 创建透明度渐变动画
const tween = new TWEEN.Tween(item)
.to({alpha: 1}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.to({ alpha: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // 使用缓动函数使动画更平滑
.onComplete(function() {
// 动画完成后执行回调
if (callBack) {
callBack();
}
});
// 设置缓动函数
if (easing) {
tween.easing(easing);
}
// 开始动画
tween.start();
}
export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = null) {
/**
* 创建透明度变化动画
* 将对象透明度变化到指定值
* @param item - 要改变透明度的对象
* @param alpha - 目标透明度值(0-1)
* @param time - 动画持续时间(秒),默认0.8秒
* @param callBack - 动画完成回调函数
* @param easing - 缓动函数
*/
export function alphaItem(
item,
alpha,
time = 0.8,
callBack = null,
easing = null
) {
// 创建透明度变化动画
const tween = new TWEEN.Tween(item)
.to({alpha}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.to({ alpha: alpha }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // 使用缓动函数使动画更平滑
.onComplete(function() {
// 动画完成后执行回调
if (callBack) {
callBack();
}
});
// 设置缓动函数
if (easing) {
tween.easing(easing);
}
// 开始动画
tween.start();
}
/**
* 创建星星显示动画
* 同时改变透明度和缩放到1
* @param item - 要显示的星星对象
* @param time - 动画持续时间(秒),默认0.8秒
* @param callBack - 动画完成回调函数
* @param easing - 缓动函数
*/
export function showStar(item, time = 0.8, callBack = null, easing = null) {
// 创建同时改变透明度和缩放的动画
const tween = new TWEEN.Tween(item)
.to({alpha: 1, scale: 1}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.to({ alpha: 1, scale: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // 使用缓动函数使动画更平滑
.onComplete(function() {
// 动画完成后执行回调
if (callBack) {
callBack();
}
});
// 设置缓动函数
if (easing) {
tween.easing(easing);
}
// 开始动画
tween.start();
}
/**
* 随机打乱数组顺序
* 使用Fisher-Yates洗牌算法的变种实现数组随机排序
* @param arr - 要打乱的原始数组
* @returns {Array} - 打乱后的新数组
*/
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;
}
/**
* 弧度转角度
* @param radian - 弧度值
* @returns {number} - 对应的角度值
*/
export function radianToAngle(radian) {
return radian * 180 / Math.PI;
return (radian * 180) / Math.PI;
// 角度 = 弧度 * 180 / Math.PI;
}
/**
* 角度转弧度
* @param angle - 角度值
* @returns {number} - 对应的弧度值
*/
export function angleToRadian(angle) {
return angle * Math.PI / 180;
return (angle * Math.PI) / 180;
// 弧度= 角度 * Math.PI / 180;
}
/**
* 根据角度和长度计算坐标点
* @param angle - 角度值(0-360)
* @param len - 距离长度
* @returns {{x: number, y: number}} - 计算得到的坐标点
*/
export function getPosByAngle(angle, len) {
const radian = angle * Math.PI / 180;
// 将角度转换为弧度
const radian = (angle * Math.PI) / 180;
// 计算x坐标(使用正弦函数)
const x = Math.sin(radian) * len;
// 计算y坐标(使用余弦函数)
const y = Math.cos(radian) * len;
return {x, y};
return { x, y };
}
/**
* 根据两点坐标计算角度
* 计算从点(px,py)到点(mx,my)的角度,以y轴正方向为0度,顺时针旋转
* @param px - 起始点x坐标
* @param py - 起始点y坐标
* @param mx - 目标点x坐标
* @param my - 目标点y坐标
* @returns {number} - 计算得到的角度(0-360)
*/
export function getAngleByPos(px, py, mx, my) {
// 计算x和y方向的距离
const x = Math.abs(px - mx);
const y = Math.abs(py - my);
// 计算两点间的直线距离
const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
// 计算余弦值
const cos = y / z;
const radina = Math.acos(cos); // 用反三角函数求弧度
let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度
if (mx > px && my > py) {// 鼠标在第四象限
// 用反三角函数求弧度
const radina = Math.acos(cos);
// 将弧度转换成角度(保留两位小数)
let angle = Math.floor((180 / (Math.PI / radina)) * 100) / 100;
// 根据目标点在不同象限调整角度值
if (mx > px && my > py) {
// 目标点在第四象限
angle = 180 - angle;
}
if (mx === px && my > py) {// 鼠标在y轴负方向上
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;
}
/**
* 从数组中移除指定元素
* @param arr - 要操作的数组
* @param item - 要移除的元素
*/
export function removeItemFromArr(arr, item) {
// 查找元素在数组中的索引
const index = arr.indexOf(item);
if (index !== -1) {
// 如果找到了元素(索引不为-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) {
/**
* 创建圆周运动动画
* 使对象围绕指定中心点进行圆周或椭圆运动
* @param item - 要进行圆周运动的对象
* @param x0 - 圆心x坐标
* @param y0 - 圆心y坐标
* @param time - 动画持续时间(秒),默认2秒
* @param addR - 旋转角度,默认360度(一周)
* @param xPer - x方向缩放比例,默认1(用于创建椭圆轨迹)
* @param yPer - y方向缩放比例,默认1(用于创建椭圆轨迹)
* @param callBack - 动画完成回调函数
* @param easing - 缓动函数
*/
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};
a += 90; // 调整角度(坐标系转换)
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(() => {
callBack();
});
}
// 设置缓动函数
if (easing) {
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;
// obj.a ++;
});
// 开始动画
tween.start();
}
/**
* 计算两点间距离
* 使用勾股定理计算两点之间的直线距离
* @param sx - 起始点x坐标
* @param sy - 起始点y坐标
* @param ex - 终点x坐标
* @param ey - 终点y坐标
* @returns {number} - 两点间的距离
*/
/**
* 计算两点间距离
* 使用勾股定理计算两点之间的直线距离
* @param sx - 起始点x坐标
* @param sy - 起始点y坐标
* @param ex - 终点x坐标
* @param ey - 终点y坐标
* @returns {number} - 两点间的距离
*/
export function getPosDistance(sx, sy, ex, ey) {
// 计算x方向距离
const _x = ex - sx;
// 计算y方向距离
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;
}
export function delayCall(second, callback) {
/**
* 延迟调用函数
* 在指定时间后执行回调函数
* @param callback - 要延迟执行的回调函数
* @param second - 延迟时间(秒)
*/
export function delayCall(callback, second) {
// 创建一个延迟执行的补间动画
const tween = new TWEEN.Tween(this)
// 设置延迟时间(毫秒)
.delay(second * 1000)
// 设置完成回调
.onComplete(() => {
if (callback) {
callback();
}
})
// 开始计时
.start();
}
export function formatTime(fmt, date) {
// "yyyy-MM-dd HH:mm:ss";
const o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); }
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1)
? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return fmt;
}
export function getMinScale(item, maxW, maxH = null) {
if (!maxH) {
maxH = maxW;
}
const sx = maxW / item.width;
const sy = maxH / item.height;
/**
* 计算等比缩放比例
* 计算对象在不超过最大长度的情况下的等比缩放比例
* @param item - 要缩放的对象
* @param maxLen - 最大允许长度
* @returns {number} - 计算得到的缩放比例
*/
export function getMinScale(item, maxLen) {
// 计算宽度方向的缩放比例
const sx = maxLen / item.width;
// 计算高度方向的缩放比例
const sy = maxLen / item.height;
// 取两个方向中较小的缩放比例,确保两个方向都不超过最大长度
const minS = Math.min(sx, sy);
return minS;
}
/**
* 创建果冻弹跳效果动画
* 通过一系列缩放变化实现物体的弹性形变效果
* @param item - 要添加果冻效果的对象
* @param time - 动画总持续时间(秒),默认0.7秒
*/
export function jelly(item, time = 0.7) {
// 如果已有果冻动画正在进行,则移除
if (item.jellyTween) {
TWEEN.remove(item.jellyTween);
}
// 计算每个阶段的时间
const t = time / 9;
// 记录原始缩放值
const baseSX = item.scaleX;
const baseSY = item.scaleY;
// 当前动画阶段索引
let index = 0;
// 递归执行各阶段动画的函数
const run = () => {
// 所有阶段完成后结束
if (index >= arr.length) {
item.jellyTween = null;
return;
}
// 获取当前阶段的参数
const data = arr[index];
const t = tweenChange(item, {scaleX: data[0], scaleY: data[1]}, data[2], () => {
index ++;
run();
}, TWEEN.Easing.Sinusoidal.InOut);
item.jellyTween = t;
};
const arr = [
[baseSX * 1.1, baseSY * 0.9, t],
[baseSX * 0.98, baseSY * 1.02, t * 2],
[baseSX * 1.02, baseSY * 0.98, t * 2],
[baseSX * 0.99, baseSY * 1.01, t * 2],
[baseSX * 1.0, baseSY * 1.0, t * 2],
];
run();
}
export function jellyPop(item, time) {
if (item.jellyTween) {
TWEEN.remove(item.jellyTween);
}
const t = time / 6;
const baseSX = item.scaleX;
const baseSY = item.scaleY;
let index = 0;
const run = () => {
if (index >= arr.length) {
item.jellyTween = null;
return;
}
const data = arr[index];
const t = tweenChange(item, {scaleX: data[0], scaleY: data[1]}, data[2], () => {
index ++;
// 创建当前阶段的缩放动画
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;
};
// 定义各阶段的缩放值和时间
// 格式:[scaleX, scaleY, duration]
const arr = [
[baseSX * 1.3, baseSY * 1.3, t],
[baseSX * 0.85, baseSY * 0.85, t * 1],
[baseSX * 1.1, baseSY * 1.1, t * 1],
[baseSX * 0.95, baseSY * 0.95, t * 1],
[baseSX * 1.02, baseSY * 1.02, t * 1],
[baseSX * 1, baseSY * 1, t * 1],
[baseSX * 1.1, baseSY * 0.9, t], // 第一阶段:横向拉伸,纵向压缩
[baseSX * 0.98, baseSY * 1.02, t * 2], // 第二阶段:横向压缩,纵向拉伸
[baseSX * 1.02, baseSY * 0.98, t * 2], // 第三阶段:横向拉伸,纵向压缩
[baseSX * 0.99, baseSY * 1.01, t * 2], // 第四阶段:轻微横向压缩,纵向拉伸
[baseSX * 1.0, baseSY * 1.0, t * 2] // 最终阶段:恢复原始大小
];
item.setScaleXY(0);
// 开始执行动画
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;
particle.y = pos.y;
// 添加到父容器
parent.addChild(particle);
// 随机旋转角度
const randomR = 360 * Math.random();
particle.rotation = randomR;
const randomS = 0.3 + Math.random() * 0.7;
particle.setScaleXY(randomS * 0.3);
// 随机缩放大小(0.5-1.0之间)
const randomS = 0.5 + Math.random() * 0.5;
particle.setScaleXY(randomS);
// 随机偏移初始位置(±10像素)
const randomX = Math.random() * 20 - 10;
particle.x += randomX;
const randomY = Math.random() * 20 - 10;
particle.y += randomY;
const randomL = minLen + Math.random() * (maxLen - minLen);
// 随机飞行距离和方向
const 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, () => {});
}
}
/**
* 创建抖动效果动画
* 使对象在短时间内进行随机位置抖动
* @param item - 要添加抖动效果的对象
* @param time - 抖动持续时间(秒),默认0.5秒
* @param callback - 抖动完成后的回调函数
* @param rate - 抖动幅度系数,默认为1
*/
export function shake(item, time = 0.5, callback = null, rate = 1) {
// 如果已有抖动动画正在进行,则不重复创建
if (item.shakeTween) {
return;
}
// 标记抖动动画正在进行
item.shakeTween = true;
// 计算抖动偏移量(基于对象缩放和传入的系数)
const offX = 15 * item.scaleX * rate;
const offY = 15 * item.scaleX * rate;
// 记录原始位置
const baseX = item.x;
const baseY = item.y;
// 使用正弦缓动函数使抖动更自然
const easing = TWEEN.Easing.Sinusoidal.InOut;
// 第四阶段:回到原始位置
const move4 = () => {
moveItem(item, baseX, baseY, time / 4, () => {
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();
}
export function getMaxScale(item, maxW, maxH) {
const sx = maxW / item.width;
const sy = maxH / item.height;
const maxS = Math.max(sx, sy);
return maxS;
}
export function createSprite(key) {
const image = window.curImages;
const spr = new MySprite();
spr.init(image.get(key));
return spr;
// --------------- 自定义类和特效函数 --------------------
/**
* 创建闪烁星星效果
* 在指定区域内周期性地显示多个闪烁星星
* @param starImg - 星星图片
* @param rectArea - 显示区域
* @param parent - 星星的父容器
* @param mapScale - 缩放系数,默认为1
* @param num - 每次显示的星星数量,默认30个
* @param disTime - 显示间隔时间(秒),默认0.1秒
* @param showTime - 效果持续总时间(秒),默认3秒
*/
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);
}
export class MyVideo extends MySprite {
element;
initVideoElement(videoElement) {
this.element = videoElement;
this.width = this.element.videoWidth;
this.height = this.element.videoHeight;
this.element.currentTime = 0.01;
}
drawSelf() {
super.drawSelf();
this.ctx.drawImage(this.element, 0, 0, this.width, this.height);
/**
* 显示一组闪烁星星
* 在指定区域内创建多个星星并执行缩放动画
* @param starImg - 星星图片
* @param num - 星星数量
* @param rectArea - 显示区域
* @param parent - 星星的父容器
* @param mapScale - 缩放系数
* @private
*/
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(4);
// 添加到父容器
parent.addChild(star);
// 第一阶段:从大到目标大小的缩放动画
scaleItem(star, randomS, 0.3, () => {
// 短暂显示后开始消失
setTimeout(() => {
// 第二阶段:缩小消失动画
scaleItem(star, 0, 0.3, () => {
// 动画完成后移除星星
parent.removeChild(star);
});
}, 100 + Math.random() * 200); // 随机持续时间
});
}
}
// --------------- custom class --------------------
.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") ;
}
This source diff could not be displayed because it is too large. You can view the blob instead.
/**
* 本地图片资源映射 - CommonJS版本
* 用于Node.js脚本中导入使用
*/
// 从原始resources.js文件中复制的内容
const localImages = {
'bg_green_small': 'assets/game/bg_green_small.png',
'bg_green_small_line': 'assets/game/bg_green_small_line.png',
'bg': 'assets/game/bg.jpg',
'bg_green': 'assets/game/bg_green.png',
'bg_green_line': 'assets/game/bg_greenline.png',
'bg_title': 'assets/game/bg_title.png',
'bg_white': 'assets/game/bg_white.png',
'bg_white_line': 'assets/game/bg_whiteline.png',
'bg_yellow': 'assets/game/bg_yellow.png',
'bg_yellow_small': 'assets/game/bg_yellow_small.png',
'bg_yellow_small_line': 'assets/game/bg_yellow_small_line.png',
'bg_yellow_line': 'assets/game/bg_yellowline.png',
'btn_return': 'assets/game/btn_return.png',
'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_500_600': "assets/default/images/bg_500_600.png",
'bg_1280_222': "assets/default/images/bg_1280_222.png",
'bg_1280_720': "assets/default/images/bg_1280_222.png",
'petal_1': "assets/default/images/scrap-pic-1.png",
'petal_2': "assets/default/images/scrap-pic-2.png",
'petal_3': "assets/default/images/scrap-pic-3.png",
'star': "assets/default/images/star.png",
'flag': "assets/default/images/flag.png",
'1': "assets/play/1.png",
'1-2': "assets/play/1-2.png",
'1-3': "assets/play/1-3.png",
'background': "assets/play/background.png",
'grass-left': "assets/play/grass-left.png",
'grass-right': "assets/play/grass-right.png",
'grass-mid-1': "assets/play/grass-mid-1.png",
'grass-mid-2': "assets/play/grass-mid-2.png",
'grass-mid-3': "assets/play/grass-mid-3.png",
'6-10': "assets/play/6-10.png",
'mike-1-2': "assets/play/mike-1-2.png",
'card-background': "assets/play/2.png",
'1-4': "assets/play/1-4.png",
'shadow-1': "assets/play/shadow-1.png",
'shadow-2': "assets/play/shadow-2.png",
'shadow-3': "assets/play/shadow-3.png",
'shadow-4': "assets/play/shadow-4.png"
};
const localAudios = {
'ssiwb_btn': 'assets/audio/ssiwb_btn.mp3',
'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',
'star': "assets/default/audio/star.mp3",
'tupiantanchu': 'assets/audio/tupiantanchu.mp3',
'houzitiaodong': 'assets/audio/houzitiaodong.mp3',
'houzitiaodongsahua': 'assets/audio/houzitiaodongsahua.mp3',
'huoziluodi': 'assets/audio/huoziluodi.wav'
};
// 图片尺寸信息对象,存储每个图片的宽度和高度
const localImagesSize = {
'1': { width: 197, height: 147 },
'bg_green_small': { width: 125, height: 119 },
'bg_green_small_line': { width: 130, height: 119 },
'bg': { width: 1280, height: 720 },
'bg_green': { width: 179, height: 171 },
'bg_green_line': { width: 182, height: 169 },
'bg_title': { width: 322, height: 85 },
'bg_white': { width: 180, height: 172 },
'bg_white_line': { width: 183, height: 169 },
'bg_yellow': { width: 303, height: 152 },
'bg_yellow_small': { width: 216, height: 107 },
'bg_yellow_small_line': { width: 217, height: 111 },
'bg_yellow_line': { width: 305, height: 155 },
'btn_return': { width: 63, height: 65 },
'bg_1280_720_Ruler': { width: 1280, height: 720 },
'bg-240-180': { width: 240, height: 180 },
'bg-453-251': { width: 453, height: 251 },
'bg_500_600': { width: 500, height: 600 },
'bg_1280_222': { width: 1280, height: 222 },
'bg_1280_720': { width: 1280, height: 222 },
'petal_1': { width: 35, height: 42 },
'petal_2': { width: 39, height: 47 },
'petal_3': { width: 36, height: 42 },
'star': { width: 62, height: 59 },
'flag': { width: 1, height: 720 },
'1-2': { width: 197, height: 147 },
'1-3': { width: 231, height: 235 },
'background': { width: 1280, height: 720 },
'grass-left': { width: 249, height: 169 },
'grass-right': { width: 257, height: 181 },
'grass-mid-1': { width: 255, height: 112 },
'grass-mid-2': { width: 161, height: 94 },
'grass-mid-3': { width: 313, height: 95 },
'6-10': { width: 44, height: 16 },
'mike-1-2': { width: 528, height: 750 },
'card-background': { width: 216, height: 251 },
'1-4': { width: 197, height: 147 },
'shadow-1': { width: 41, height: 22 },
'shadow-2': { width: 49, height: 22 },
'shadow-3': { width: 38, height: 19 },
'shadow-4': { width: 47, height: 18 },
};
// 使用CommonJS模块导出
module.exports = { localImages, localAudios, localImagesSize };
\ No newline at end of file
const res = [
/**
* 本地图片资源映射
* 键名为图片在代码中的引用名称,键值为图片文件的实际路径
*/
const localImages = {
'bg_green_small': 'assets/game/bg_green_small.png',
'bg_green_small_line': 'assets/game/bg_green_small_line.png',
'bg': 'assets/game/bg.jpg',
'bg_green': 'assets/game/bg_green.png',
'bg_green_line': 'assets/game/bg_greenline.png',
'bg_title': 'assets/game/bg_title.png',
'bg_white': 'assets/game/bg_white.png',
'bg_white_line': 'assets/game/bg_whiteline.png',
'bg_yellow': 'assets/game/bg_yellow.png',
'bg_yellow_small': 'assets/game/bg_yellow_small.png',
'bg_yellow_small_line': 'assets/game/bg_yellow_small_line.png',
'bg_yellow_line': 'assets/game/bg_yellowline.png',
'btn_return': 'assets/game/btn_return.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_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_500_600': "assets/default/images/bg_500_600.png",
'bg_1280_222': "assets/default/images/bg_1280_222.png",
'bg_1280_720': "assets/default/images/bg_1280_222.png",
'petal_1': "assets/default/images/scrap-pic-1.png",
'petal_2': "assets/default/images/scrap-pic-2.png",
'petal_3': "assets/default/images/scrap-pic-3.png",
'star': "assets/default/images/star.png",
'flag': "assets/default/images/flag.png",
];
'1': "assets/play/1.png",
'1-2': "assets/play/1-2.png",
'1-3': "assets/play/1-3.png",
'background': "assets/play/background.png",
'grass-left': "assets/play/grass-left.png",
'grass-right': "assets/play/grass-right.png",
'grass-mid-1': "assets/play/grass-mid-1.png",
'grass-mid-2': "assets/play/grass-mid-2.png",
'grass-mid-3': "assets/play/grass-mid-3.png",
'6-10': "assets/play/6-10.png",
'mike-1-2': "assets/play/mike-1-2.png",
'card-background': "assets/play/2.png",
'1-4': "assets/play/1-4.png",
'shadow-1': "assets/play/shadow-1.png",
'shadow-2': "assets/play/shadow-2.png",
'shadow-3': "assets/play/shadow-3.png",
'shadow-4': "assets/play/shadow-4.png"
};
const resAudio = [
const localAudios = {
'ssiwb_btn': 'assets/audio/ssiwb_btn.mp3',
'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',
'star': "assets/default/audio/star.mp3",
['click', "assets/play/music/click.mp3"],
'tupiantanchu': 'assets/audio/tupiantanchu.mp3',
'houzitiaodong': 'assets/audio/houzitiaodong.mp3',
'houzitiaodongsahua': 'assets/audio/houzitiaodongsahua.mp3',
'huoziluodi': 'assets/audio/huoziluodi.wav'
};
];
// 图片尺寸信息对象,存储每个图片的宽度和高度
const localImagesSize = {
'1': { width: 197, height: 147 },
'bg_green_small': { width: 130, height: 119 },
'bg_green_small_line': { width: 130, height: 119 },
'bg': { width: 1280, height: 720 },
'bg_green': { width: 182, height: 171 },
'bg_green_line': { width: 182, height: 169 },
'bg_title': { width: 322, height: 85 },
'bg_white': { width: 183, height: 172 },
'bg_white_line': { width: 183, height: 169 },
'bg_yellow': { width: 305, height: 152 },
'bg_yellow_small': { width: 217, height: 107 },
'bg_yellow_small_line': { width: 217, height: 111 },
'bg_yellow_line': { width: 305, height: 155 },
'btn_return': { width: 63, height: 65 },
'bg_1280_720_Ruler': { width: 1280, height: 720 },
'bg-240-180': { width: 240, height: 180 },
'bg-453-251': { width: 453, height: 251 },
'bg_500_600': { width: 500, height: 600 },
'bg_1280_222': { width: 1280, height: 222 },
'bg_1280_720': { width: 1280, height: 222 },
'petal_1': { width: 35, height: 42 },
'petal_2': { width: 39, height: 47 },
'petal_3': { width: 36, height: 42 },
'star': { width: 62, height: 59 },
'flag': { width: 1, height: 720 },
'1-2': { width: 197, height: 147 },
'1-3': { width: 231, height: 235 },
'background': { width: 1280, height: 720 },
'grass-left': { width: 249, height: 169 },
'grass-right': { width: 257, height: 181 },
'grass-mid-1': { width: 255, height: 112 },
'grass-mid-2': { width: 161, height: 94 },
'grass-mid-3': { width: 313, height: 95 },
'6-10': { width: 44, height: 16 },
'mike-1-2': { width: 528, height: 750 },
'card-background': { width: 216, height: 251 },
'1-4': { width: 197, height: 147 },
'shadow-1': { width: 41, height: 22 },
'shadow-2': { width: 49, height: 22 },
'shadow-3': { width: 38, height: 19 },
'shadow-4': { width: 47, height: 18 },
};
export {res, resAudio};
export {localImages, localAudios, localImagesSize};
/**
* 图片尺寸更新脚本
* 用于读取assets/game目录下的图片尺寸并更新resources.js文件中的localImagesSize对象
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
// 项目根目录路径
const rootDir = path.resolve(__dirname, '../..');
// 从CommonJS版本的resources.cjs.js导入图片路径映射
const { localImages } = require('./resources.cjs.js');
// 创建一个新的localImagesSize对象
const localImagesSize = {};
// 使用sips命令读取图片尺寸(macOS系统专用)
function getImageDimensions(imagePath) {
try {
const fullPath = path.join(rootDir, imagePath);
if (!fs.existsSync(fullPath)) {
console.warn(`图片不存在: ${fullPath}`);
return null;
}
// 使用macOS的sips命令获取图片尺寸
const output = execSync(`sips -g pixelWidth -g pixelHeight "${fullPath}" | grep pixel`).toString();
const widthMatch = output.match(/pixelWidth: (\d+)/);
const heightMatch = output.match(/pixelHeight: (\d+)/);
if (widthMatch && heightMatch) {
return {
width: parseInt(widthMatch[1], 10),
height: parseInt(heightMatch[1], 10)
};
}
return null;
} catch (error) {
console.error(`读取图片尺寸失败: ${imagePath}`, error);
return null;
}
}
// 更新resources.js文件的函数
function updateResourcesFile(imageSizes) {
// 更新ES模块版本的resources.js
updateESModuleFile(imageSizes);
// 更新CommonJS版本的resources.cjs.js
updateCommonJSFile(imageSizes);
console.log('所有资源文件已更新');
}
// 更新ES模块版本的resources.js
function updateESModuleFile(imageSizes) {
const resourcesFilePath = path.join(__dirname, 'resources.js');
let content = fs.readFileSync(resourcesFilePath, 'utf8');
// 构建localImagesSize对象字符串
let sizeObjectStr = 'const localImagesSize = {\n';
Object.keys(imageSizes).forEach(key => {
const size = imageSizes[key];
if (size) {
sizeObjectStr += ` '${key}': { width: ${size.width}, height: ${size.height} },\n`;
} else {
// 如果无法获取尺寸,使用默认值或保留现有值
sizeObjectStr += ` '${key}': { width: 0, height: 0 }, // 无法获取尺寸\n`;
}
});
sizeObjectStr += '};';
// 替换或添加localImagesSize对象
const sizeRegex = /const localImagesSize = \{[\s\S]*?\};/;
if (content.match(sizeRegex)) {
content = content.replace(sizeRegex, sizeObjectStr);
console.log('已更新resources.js中现有的localImagesSize对象');
} else {
// 在文件末尾添加localImagesSize对象,但在export语句之前
const exportMatch = content.match(/export \{([^}]*)\};/);
if (exportMatch) {
// 提取导出的变量列表
const exportedVars = exportMatch[1].split(',').map(v => v.trim());
// 添加localImagesSize到导出列表
if (!exportedVars.includes('localImagesSize')) {
exportedVars.push('localImagesSize');
}
// 构建新的导出语句
const newExport = `export {${exportedVars.join(', ')}};`;
// 替换原有的导出语句
content = content.replace(/export \{[^}]*\};/, `\n${sizeObjectStr}\n\n${newExport}`);
console.log('已添加localImagesSize对象并更新resources.js的导出语句');
} else {
// 如果没有找到export语句,则在文件末尾添加
content += `\n${sizeObjectStr}\n\nexport {localImages, localAudios, localImagesSize};`;
console.log('已在resources.js文件末尾添加localImagesSize对象和ES模块导出');
}
}
fs.writeFileSync(resourcesFilePath, content, 'utf8');
console.log('resources.js文件已更新');
}
// 更新CommonJS版本的resources.cjs.js
function updateCommonJSFile(imageSizes) {
const resourcesFilePath = path.join(__dirname, 'resources.cjs.js');
let content = fs.readFileSync(resourcesFilePath, 'utf8');
// 构建localImagesSize对象字符串
let sizeObjectStr = 'const localImagesSize = {\n';
Object.keys(imageSizes).forEach(key => {
const size = imageSizes[key];
if (size) {
sizeObjectStr += ` '${key}': { width: ${size.width}, height: ${size.height} },\n`;
} else {
// 如果无法获取尺寸,使用默认值或保留现有值
sizeObjectStr += ` '${key}': { width: 0, height: 0 }, // 无法获取尺寸\n`;
}
});
sizeObjectStr += '};';
// 替换或添加localImagesSize对象
const sizeRegex = /const localImagesSize = \{[\s\S]*?\};/;
if (content.match(sizeRegex)) {
content = content.replace(sizeRegex, sizeObjectStr);
console.log('已更新resources.cjs.js中现有的localImagesSize对象');
} else {
// 在module.exports前添加localImagesSize对象
const exportMatch = content.match(/module\.exports = \{([^}]*)\};/);
if (exportMatch) {
// 提取导出的变量列表
const exportedVars = exportMatch[1].split(',').map(v => v.trim());
// 添加localImagesSize到导出列表(如果尚未添加)
if (!exportedVars.includes('localImagesSize')) {
exportedVars.push('localImagesSize');
}
// 构建新的导出语句
const newExport = `module.exports = {${exportedVars.join(', ')}};`;
// 替换原有的导出语句
content = content.replace(/module\.exports = \{[^}]*\};/, `${sizeObjectStr}\n\n${newExport}`);
console.log('已添加localImagesSize对象并更新resources.cjs.js的导出语句');
} else {
// 如果没有找到module.exports语句,则在文件末尾添加
content += `\n${sizeObjectStr}\n\nmodule.exports = { localImages, localAudios, localImagesSize };`;
console.log('已在resources.cjs.js文件末尾添加localImagesSize对象和CommonJS导出');
}
}
fs.writeFileSync(resourcesFilePath, content, 'utf8');
console.log('resources.cjs.js文件已更新');
}
// 主函数
function main() {
console.log('开始读取图片尺寸...');
// 处理所有图片
Object.entries(localImages).forEach(([key, imagePath]) => {
const dimensions = getImageDimensions(imagePath);
localImagesSize[key] = dimensions;
console.log(`读取图片 ${key}: ${dimensions ? `${dimensions.width}x${dimensions.height}` : '失败'}`);
});
// 更新resources.js文件
updateResourcesFile(localImagesSize);
console.log('所有图片尺寸已更新');
}
// 执行主函数
try {
main();
} catch (error) {
console.error('更新图片尺寸时发生错误:', error);
}
\ No newline at end of file
import {
MySprite,
getMinScale,
ShapeRect,
tweenChange,
randomSortByArr,
Label,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem
} from "./Unit";
const myUtility = {};
// 系统缩放比例
myUtility.mapScale = 1;
// 音乐 和 图片的缓冲区
myUtility.audio = new Map();
myUtility.images = new Map();
myUtility.imagesOriginSize = new Map();
// 坐标原点 包含缩放
myUtility.originX = 0;
myUtility.originY = 0;
myUtility.setOrigin = (x, y)=>{
myUtility.originX = x;
myUtility.originY = y;
}
myUtility.getOrigin = ()=>{
return {
x: myUtility.originX,
y: myUtility.originY
}
}
// 坐标原点 包含缩放
myUtility.relativeOriginX = 0;
myUtility.relativeOriginY = 0;
myUtility.setRelativeOrigin = (x, y)=>{
myUtility.relativeOriginX = x;
myUtility.relativeOriginY = y;
}
myUtility.getRelativeOrigin = ()=>{
return {
x: myUtility.relativeOriginX,
y: myUtility.relativeOriginY
}
}
// 存放音乐和图片的地址
const audioObj = {}
const imageObj = {}
// 添加音乐
myUtility.audio.add = ( key, url ) => {
audioObj[key] = url
};
// 添加音乐
myUtility.images.add = ( key, url ) => {
imageObj[key] = url
};
// 播放音乐
myUtility.audio.playAudio = function(key, now = false, callback = null) {
const audio = myUtility.audio.get(key);
if (audio) {
if (now) {
audio.pause();
audio.currentTime = 0;
}
if (callback) {
audio.onended = () => {
callback();
};
}
audio.play();
}
}
// 异步加载图片 音频资源
myUtility.loadResources = ()=> {
const pr = [];
for(let key in imageObj){
const p = preloadImage(imageObj[key]).then(img => {
myUtility.images.set(key, img);
myUtility.imagesOriginSize.set(key, {width:img.width, height:img.height});
}).catch(err => console.log(key));
pr.push(p);
};
for(let key in audioObj){
const a = preloadAudio(audioObj[key]).then((music) => {
myUtility.audio.set(key, music);
}).catch(err => console.log(key));
pr.push(a);
};
return Promise.all(pr);
}
// 预加载图片
const preloadImage = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
}
// 预加载音频
const preloadAudio = (url) => {
return new Promise((resolve, reject) => {
const audio = new Audio();
audio.oncanplay = a => {
resolve(audio);
};
audio.onerror = () => {
reject();
};
audio.src = url;
audio.load();
});
}
// 缓存页面元素
myUtility.cartoonElementsBuffer = {}
myUtility.createCartoonElement = (key, element, width, heigth, initX, initY)=>{
myUtility.cartoonElementsBuffer[key] = {}
myUtility.cartoonElementsBuffer[key].id = key;
myUtility.cartoonElementsBuffer[key].width = width;
myUtility.cartoonElementsBuffer[key].heigth = heigth;
myUtility.cartoonElementsBuffer[key].initX = initX;
myUtility.cartoonElementsBuffer[key].initY = initY;
myUtility.cartoonElementsBuffer[key].ref = element;
return myUtility.cartoonElementsBuffer[key]
}
myUtility.getCartoonElementRef = (key)=>{
if(myUtility.cartoonElementsBuffer[key]){
return myUtility.cartoonElementsBuffer[key].ref;
}else{
return undefined
}
}
myUtility.getCartoonElement = (key)=>{
return myUtility.cartoonElementsBuffer[key]
}
myUtility.setCartoonElementPosition = (key, posi)=>{
myUtility.cartoonElementsBuffer[key].ref.x = posi.x
myUtility.cartoonElementsBuffer[key].ref.y = posi.y
myUtility.cartoonElementsBuffer[key].x = posi.x
myUtility.cartoonElementsBuffer[key].y = posi.y
}
myUtility.setCartoonElementPositionX = (key, x)=>{
myUtility.cartoonElementsBuffer[key].ref.x = x
myUtility.cartoonElementsBuffer[key].x = x
}
myUtility.setCartoonElementRelativePositionX = (key, x)=>{
myUtility.cartoonElementsBuffer[key].relativeX = x
}
myUtility.setCartoonElementPositionY = (key, y)=>{
myUtility.cartoonElementsBuffer[key].ref.y = y
myUtility.cartoonElementsBuffer[key].y = y
}
myUtility.setCartoonElementRelativePositionY = (key, y)=>{
myUtility.cartoonElementsBuffer[key].relativeY = y
}
myUtility.getCartoonElementPosition = (key)=>{
return {
x: myUtility.cartoonElementsBuffer[key].x,
y: myUtility.cartoonElementsBuffer[key].y
}
}
myUtility.getCartoonElementRelativePosition = (key)=>{
return {
x: myUtility.cartoonElementsBuffer[key].relativeX,
y: myUtility.cartoonElementsBuffer[key].relativeY
}
}
myUtility.animation = {}
myUtility.animation.move = (eleKey, distPosition, runTime, callback )=>{
tweenChange(myUtility.cartoonElementsBuffer[eleKey].ref, distPosition, runTime, ()=>{
callback && callback()
});
}
myUtility.animation.scaleChange = myUtility.animation.move;
export default myUtility
/*
global css to mixin
*/
/* @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;
}
@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;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!DOCTYPE html>
<html lang="zh">
<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="https://teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air.js" ></script>
</head>
<body>
<app-root></app-root>
</body>
</html>
/* You can add global styles to this file, and also import other style files */
@import "~ng-zorro-antd/ng-zorro-antd.min.css";
\ No newline at end of file
......@@ -21,6 +21,7 @@
]
},
"angularCompilerOptions": {
"enableIvy": false,
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
......
......@@ -92,8 +92,7 @@
"variable-name": false,
"no-unused-expression": false,
"align": false,
"no-string-literal": false
"align": false
},
"rulesDirectory": [
"codelyzer"
......
1. anglar 帮我给左中右对应的字母组都加上勾选项目, 勾选内容为是否默认显示。
2. 读取 assets/default/images/game/ 目录下的文件名称 生成如 resources.js 中的配置文件中的 bg_green_small类似的配置。
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