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

dev commit

parent 9f3a2900
@import '../style/common_mixin.css';
.model-content {
width: 100%;
height: 100%;
}
<div class="model-content" style="min-width: 850px;">
<div class="card-config">
<div class="card-item">
<div class="card-item-content">
<div class="title">模板配置</div>
<div *ngIf="dataArray.length>0" class="section" style="padding: 1rem;">
<nz-form-item>
<nz-form-control [nzSpan]="4">
<div class="text-label">格子数量(宽*高)</div>
</nz-form-control>
<nz-form-control [nzSpan]="20">
<div style="width: 100px">
<nz-select [(ngModel)]="size.wh" style="width: 100%;" (ngModelChange)="handleGirdSizeChange()">
<nz-option nzValue="9*9" nzLabel="9 * 9"></nz-option>
<nz-option nzValue="12*12" nzLabel="12 * 12"></nz-option>
<nz-option nzValue="15*15" nzLabel="15 * 15"></nz-option>
<nz-option nzValue="17*17" nzLabel="17 * 17"></nz-option>
</nz-select>
</div>
</nz-form-control>
</nz-form-item>
<div class="model-content"> <nz-form-item>
<nz-form-control [nzSpan]="4">
<div class="text-label">题号选择</div>
</nz-form-control>
<nz-form-control [nzSpan]="20">
<nz-radio-group [(ngModel)]="currentSet" nzButtonStyle="solid" (ngModelChange)="handleCurrentIndexChange()">
<label *ngFor="let item of dataArray; let i = index" nz-radio-button [nzValue]="i">{{i+1}}</label>
</nz-radio-group>
<button nz-button nzShape="circle" style="margin-left: 10px;" (click)="addItem()"><i nz-icon nzType="plus"></i></button>
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-control [nzSpan]="4">
<div class="text-label">文字提示</div>
</nz-form-control>
<nz-form-control [nzSpan]="20">
<div *ngFor="let item of dataArray; let i = index">
<textarea *ngIf="i==currentSet" [(ngModel)]="item.text" nz-input nzAutosize (blur)="saveItem()"></textarea>
</div>
</nz-form-control>
</nz-form-item>
<div style="position: absolute; left: 200px; top: 100px; width: 800px;"> <nz-form-item>
<nz-form-control [nzSpan]="4">
<div class="text-label">填空设置</div>
</nz-form-control>
<nz-form-control [nzSpan]="20">
<div *ngFor="let oneRow of grid; let x = index" class="clearfix">
<div *ngFor="let oneGrid of oneRow; let y = index" style="float: left; padding: 2px;">
<input style="width: 38px" (focus)="selectContent($event)" class="inputBlock" [disabled]="(oneGrid.index != currentSet && oneGrid.index!=-1)" [maxLength]="1" type="text" nz-input [(ngModel)]="oneGrid.text" (blur)="handeGridChange($event, oneGrid, x, y)" >
</div>
</div>
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-control [nzSpan]="4">
</nz-form-control>
<nz-form-control [nzSpan]="20">
<button nz-button nzSize="small" nzType="primary" (click)="resetByIndex(currentSet,false)">清除本题已填写字母</button>
<button nz-button nzSize="small" [disabled]="dataArray.length==1" nzType="danger" style="margin-left: 10px;" (click)="deleteByIndex(currentSet)"><i nz-icon nzType="delete"></i>删除本题</button>
</nz-form-control>
</nz-form-item>
<input type="text" nz-input [(ngModel)]="item.text" (blur)="save()"> </div>
</div>
<app-upload-image-with-preview </div>
[picUrl]="item.pic_url"
(imageUploaded)="onImageUploadSuccess($event, 'pic_url')"
></app-upload-image-with-preview>
<app-audio-recorder
[audioUrl]="item.audio_url"
(audioUploaded)="onAudioUploadSuccess($event, 'audio_url')"
></app-audio-recorder>
<app-custom-hot-zone></app-custom-hot-zone>
<app-upload-video></app-upload-video>
<app-lesson-title-config></app-lesson-title-config>
</div> </div>
</div>
</div> \ No newline at end of file
\ No newline at end of file
@import "../style/common_mixin";
.model-content {
margin: 10px;
.card-config {
width: 100%;
height: 100%;
display: flex;
flex-wrap: wrap;
box-sizing: border-box;
flex-direction:column;
.card-item{
flex:1;
margin: 1rem;
.card-item-content{
.title {
font-size: 24px;
width: 100%;
text-align: center;
}
.section{
border-top: 1px solid ;
padding: 10px 0;
.section-title{
font-size: 24px;
width: 100%;
}
.section-content{
display: flex;
margin: 5px 0 10px 0;
}
}
.pic-sound-box {
width: 50%;
display: flex;
flex-direction: column;
}
.add-btn-box {
display: flex;
align-items: center;
justify-content: center;
height: 20vw;
padding: 10px;
padding-top: 5vw;
}
}
}
}
}
.border {
border-radius: 20px;
border-style: dashed;
padding:20px;
width: 100%;
}
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.form-item p{
padding-left: 100px;
position: relative;
span {
position: absolute;
left: 0;
font-weight: bold;
}
}
.highLight {
background-color: #ff0;
}
.index-button {
margin: 0 5px;
}
.text-label {
text-align: right;
padding-right: 20px;
position: relative;
}
.text-label::after {
content: ":";
position: absolute;
right: 10px;
}
.ant-input-disabled, .ant-input[disabled] {
background-color: #702ff4;
opacity: 0.5;
cursor: not-allowed;
color: #FFF;
}
.inputBlock{
cursor: pointer;
color: transparent;
text-shadow: 0 0 0 #000;
}
import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef} from '@angular/core'; import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ElementRef, ViewChild} from '@angular/core';
import { defaultData } from '../../assets/default/formData/DataKey_JM04_3.js'
import { v4 as uuidv4 } from 'uuid';
import { NzTreeModule } from 'ng-zorro-antd';
import { fas } from '@fortawesome/free-solid-svg-icons';
@Component({ @Component({
selector: 'app-form', selector: 'app-form',
templateUrl: './form.component.html', templateUrl: './form.component.html',
styleUrls: ['./form.component.css'] styleUrls: ['./form.component.scss']
}) })
export class FormComponent implements OnInit, OnChanges, OnDestroy {
// 储存数据用
saveKey = "test_0011";
// 储存对象
item;
export class FormComponent implements OnInit, OnChanges, OnDestroy {
constructor(private appRef: ApplicationRef,private changeDetectorRef: ChangeDetectorRef) { _item: any;
KEY = 'DataKey_JM04_3';
currentQT: {text}
set item(item) {
this._item = item;
}
get item() {
return this._item;
}
dataArray = []
grid = []
title = {
"NO": "C",
"mainText": "",
"mainTextAudio_url": ""
};
size: {
wh:"12*12"
};
currentSet: number = -1;
enableRowIndex = -1;
enableColIndex = -1;
colNum = 12;
rowNum = 12;
@Output()
update = new EventEmitter();
directionMap = {
"up": "",
"down": "",
"left": "",
"right": ""
} }
constructor(private appRef: ApplicationRef) {
}
ngOnInit() { ngOnInit() {
this.item = {}; this.item = {};
this.item.contentObj = {};
// 获取存储的数据 const getData = (<any> window).courseware.getData;
(<any> window).courseware.getData((data) => { getData((data) => {
// console.log("读取数据", data)
if (data) { if (data) {
this.item = data; this.item = data;
} else {
this.item = {};
}
if ( !this.item.contentObj ) {
this.item.contentObj = {};
} }
this.init(); this.init();
this.changeDetectorRef.markForCheck();
this.changeDetectorRef.detectChanges();
this.refresh(); this.refresh();
if(this.dataArray.length>0) {
this.currentSet = 0
}
// this.saveItem()
}, this.KEY);
}
ngOnChanges() {
}, this.saveKey); }
ngOnDestroy() {
} }
init() {
const fields = ["dataArray", "grid", "title", "size"]
if(typeof(this.item.contentObj.dataArray) == undefined || typeof(this.item.contentObj.grid) == undefined || typeof(this.item.contentObj.title) == undefined || this.item.contentObj.version != defaultData.version) {
console.log("Init defalue data")
this.item.contentObj = defaultData
this.copyFieldsValue(fields, defaultData, this)
} else {
console.log("Data loaded")
this.copyFieldsValue(fields, this.item.contentObj, this)
}
console.log(this.item)
}
ngOnChanges() { disableInput(row, col) {
if(this.currentSet==-1) {
return true
} else {
let currentIndex = this.getIndexNumberByIndex(this.currentSet)
let dir = this.getDirectionByIndex(this.currentSet)
let res = false;
switch(dir) {
case "up":
if(col==currentIndex.colIndex) {
if(row>currentIndex.rowIndex) {
res= true;
} else {
res = false
}
} else {
res = true;
}
break;
case "down":
if(col==currentIndex.colIndex) {
if(row<currentIndex.rowIndex) {
res= true;
} else {
res = false
}
} else {
res = true;
}
break;
case "left":
if(row==currentIndex.rowIndex) {
if(col>currentIndex.colIndex) {
res= true;
} else {
res = false
}
} else {
res = true;
}
break;
case "right":
if(row==currentIndex.rowIndex) {
if(col<currentIndex.colIndex) {
res= true;
} else {
res = false
}
} else {
res = true;
}
break;
default: res = false;
}
if(res) {
if(this.currentSet>=0) {
this.grid[row][col].index = -1
if(this.grid[row][col].index == 0) {
this.grid[row][col].text = ""
}
this.saveItem()
}
}
return res
}
} }
ngOnDestroy() { handeGridChange(e, item, row, col) {
if(item.text != "" && e.target.value != "") {
item.index = this.currentSet
} else {
item.index = -1;
}
this.saveItem()
}
resetByIndex(index, del) {
for(let i=0; i<this.grid.length; i++) {
for(let j=0; j<this.grid[i].length; j++) {
if(this.grid[i][j].index == index) {
this.grid[i][j].index = -1; // = {index: -1, text: ""}
this.grid[i][j].text = "";
}
if(del) {
if(this.grid[i][j].index > index) {
this.grid[i][j].index--;
}
}
}
}
// this.grid = JSON.parse(JSON.stringify(this.grid))
this.saveItem();
} }
deleteByIndex(index) {
if(this.dataArray.length>1) {
this.resetByIndex(index, true);
this.dataArray.splice(index, 1);
this.currentSet = 0;
this.saveItem();
}
}
selectContent(e) {
e.target.select()
}
init() { handleGirdSizeChange() {
let col = Number(this.size.wh.split("*")[0]);
let row = Number(this.size.wh.split("*")[1]);
let _grid = []
for(let i=0; i<row; i++) {
_grid[i] = [];
for(let j=0; j<col; j++) {
_grid[i].push({index: -1, text: ""});
}
}
for(let i=0; i<this.grid.length; i++) {
for(let j=0; j<this.grid[i].length; j++) {
if(_grid[i]!=undefined && _grid[i][j]!=undefined) {
_grid[i][j].index = this.grid[i][j].index;
_grid[i][j].text = this.grid[i][j].text;
}
}
}
this.grid = JSON.parse(JSON.stringify(_grid));
this.item.contentObj.grid = this.grid;
this.saveItem();
};
getIndexNumberByIndex(numberIndex) {
let number = {
status: false,
rowIndex: -1,
colIndex: -1
}
let gotIt = false;
this.grid.forEach((row, rowIndex)=>{
row.forEach((item, colIndex) => {
if(item.index == numberIndex) {
if(!gotIt && item.text) {
gotIt = true;
number.status = true;
number.rowIndex = rowIndex
number.colIndex = colIndex
}
}
})
})
return number
} }
getDirectionByIndex(index) {
if(index==-1) {
return ""
}
let numIndex = this.getIndexNumberByIndex(index);
if(!numIndex.status) {
return ""
}
// 检查上格
if(numIndex.rowIndex-1 != -1) {
if(this.grid[numIndex.rowIndex-1][numIndex.colIndex].index == numIndex){
return "up"
}
} else {
return "down"
}
// 检查下格
if(numIndex.rowIndex+1 != this.rowNum) {
if(this.grid[numIndex.rowIndex+1][numIndex.colIndex].index == numIndex){
return "down"
}
}
// 检查左格
if(numIndex.colIndex-1 != -1) {
if(this.grid[numIndex.rowIndex][numIndex.colIndex-1].index == numIndex){
return "left"
}
} else {
return "right"
}
// 检查右格
if(numIndex.colIndex+1 != this.colNum) {
if(this.grid[numIndex.rowIndex][numIndex.colIndex+1].index == numIndex){
return "right"
}
}
/** return ""
* 储存图片数据 }
* @param e
*/
onImageUploadSuccess(e, key) {
this.item[key] = e.url; getHighlightInput(item) {
this.save(); if(item.index == this.currentSet) {
return {highLight: true}
} else {
return {highLight: false}
}
} }
/** handleCurrentIndexChange() {
* 储存音频数据
* @param e
*/
onAudioUploadSuccess(e, key) {
this.item[key] = e.url;
this.save();
} }
addItem() {
this.dataArray.push({ image_url: "", audio_url: "", text: "", uuid: uuidv4(), direction: "left" })
this.currentSet = this.dataArray.length-1;
this.saveItem();
}
cleanCurrentText() {
this.grid.forEach(row=>{
row.forEach(item => {
if(item.index == this.currentSet) {
item.index = -1;
item.text = "";
}
});
})
this.saveItem()
}
deleteItem(index) {
this.grid.forEach(row=>{
row.forEach(item => {
if(item.index == this.currentSet) {
item.index = -1;
item.text = "";
}
});
})
this.dataArray.splice(index, 1)
if(this.dataArray.length>=0){
this.currentSet = 0;
}
this.saveItem()
}
handleMoveItemUp(index) {
if (index != 0) {
this.dataArray[index] = this.dataArray.splice(index - 1, 1, this.dataArray[index])[0];
} else {
this.dataArray.push(this.dataArray.shift());
}
this.saveItem()
}
handleMoveItemDown(index) {
if (index != this.dataArray.length - 1) {
this.dataArray[index] = this.dataArray.splice(index + 1, 1, this.dataArray[index])[0];
} else {
this.dataArray.unshift(this.dataArray.splice(index, 1)[0]);
}
this.saveItem()
}
onImageUploadSuccess(e, key, item?) {
if(item) {
item[key] = e.url;
} else {
this[key] = e.url;
}
this.saveItem();
}
onAudioUploadSuccess(e, key, item?) {
if(item) {
item[key] = e.url;
} else {
this[key] = e.url;
}
this.saveItem();
}
copyFieldsValue(fields: Array<String>, from: Object, to: Object) {
fields.forEach((name: any)=>{
to[name] = from[name]
})
}
saveItem() {
// this.dataArray.forEach((item, index)=>{
// item.direction = this.getDirectionByIndex(index);
// })
this.save()
}
/**
* 储存数据
*/
save() { save() {
(<any> window).courseware.setData(this.item, null, this.saveKey); (<any> window).courseware.setData(this.item, null, this.KEY);
this.refresh(); this.refresh();
/* Remove this when commit */
// if(location.href.indexOf("localhost") != -1) {
// (<any> window).axios.post(`http://www.datalist.com.cn:8060/json/save/${this.KEY}`, this.item)
// }
/* Remove this when commit */
// console.log(JSON.stringify(this.item))
console.log("保存", this.item)
} }
/**
* 刷新 渲染页面
*/
refresh() { refresh() {
setTimeout(() => { setTimeout(() => {
this.appRef.tick(); this.appRef.tick();
}, 1); }, 1);
} }
} }
import {
MySprite,
getMinScale,
ShapeRect,
tweenChange,
randomSortByArr,
Label,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem,
ShapeRectNew,
waterWave,
ShapeCircle,
MyAnimation
} from "./Unit";
// import { matchesElement } from '@angular/animations/browser/src/render/shared';
export class Cartoon {
// 系统缩放比例
mapScale = 1;
stageWidth;
stageHeight;
clientWidth;
clientHeight;
// 音乐 和 图片的缓冲区
audio = new Map();
images = new Map();
imagesOriginSize = new Map();
// 坐标原点 包含缩放
originX = 0;
originY = 0;
setOrigin = (x, y) => {
this.originX = x;
this.originY = y;
}
getOrigin = () => {
return {
x: this.originX,
y: this.originY
}
}
// 相对坐标原点 包含缩放 用于添加孩子动画元素
relativeOriginX = 0;
relativeOriginY = 0;
setRelativeOrigin = (x, y) => {
this.relativeOriginX = x;
this.relativeOriginY = y;
}
getRelativeOrigin = () => {
return {
x: this.relativeOriginX,
y: this.relativeOriginY
}
}
// 存放音乐和图片的地址
audioObj = {}
imageObj = {}
_currentPlayAudio;
// 添加音乐
addAudio = (key, url) => {
this.audioObj[key] = url
};
// 添加音乐
addImage = (key, url) => {
this.imageObj[key] = url
};
// 播放音乐
_playingNow = []
audioCallback = {}
playAudio = function (key, now = false, callback = null, loop?, onplayingCallback?) {
const audio = this.audio.get(key);
if (audio) {
if (now) {
audio.pause();
audio.currentTime = 0;
}
this.audioCallback[key] = {}
if (callback) {
this.audioCallback[key]["onended"] = () => {
callback && callback()
}
audio.onended = () => {
let index = this._playingNow.indexOf(audio)
if (index != -1) {
this._playingNow.splice(index, 1)
}
callback();
};
}
if (onplayingCallback) {
this.audioCallback[key]["onplaying"] = () => {
onplayingCallback && onplayingCallback(audio)
}
audio.onplaying = () => {
onplayingCallback && onplayingCallback(audio)
}
}
audio.play();
audio.callback = callback
audio.loop = loop ? true : false
this._playingNow.push(audio)
this._currentPlayAudio = audio;
}
return audio
}
setAudioVolume(key, volume) {
if (volume < 0 || volume > 1) {
return
}
const audio = this.audio.get(key);
audio.volume = volume
}
stopAllAudio(audioAll?) {
if (!audioAll) {
audioAll = this._playingNow
}
audioAll.forEach(audio => {
if (audio) {
const audio_URL = audio.src
try {
if (audio) {
audio.onended && audio.onended()
audio.pause && audio.pause();
audio.currentTime = 0;
} else {
if (this.audioCallback[audio_URL] && this.audioCallback[audio_URL]["onended"]) {
this.audioCallback[audio_URL]["onended"]()
}
}
} catch (err) {
console.log(err)
}
}
else if (this._currentPlayAudio) {
this._currentPlayAudio.pause();
this._currentPlayAudio.currentTime = 0;
}
})
this._playingNow = []
}
stopAudio(audio_URL?) {
if (audio_URL) {
const audio = this.audio.get(audio_URL);
try {
if (audio) {
audio.onended && audio.onended()
audio.pause();
audio.currentTime = 0;
} else {
if (this.audioCallback[audio_URL] && this.audioCallback[audio_URL]["onended"]) {
this.audioCallback[audio_URL]["onended"]()
}
}
} catch (err) {
console.log(err)
}
}
else if (this._currentPlayAudio) {
this._currentPlayAudio.pause();
this._currentPlayAudio.currentTime = 0;
}
}
pauseAudio(key) {
const audio = this.audio.get(key);
audio.pause()
}
// 异步加载图片 音频资源
loadResources = () => {
const pr = [];
for (let key in this.imageObj) {
const p = this.preloadImage(this.imageObj[key]).then((img: any) => {
this.images.set(key, img);
this.imagesOriginSize.set(key, { width: img.width, height: img.height });
}).catch(err => console.log(key));
pr.push(p);
};
for (let key in this.audioObj) {
const a = this.preloadAudio(this.audioObj[key]).then((audio: any) => {
this.audio.set(key, audio);
}).catch(err => console.log(key));
pr.push(a);
};
return Promise.all(pr);
}
// 预加载图片
preloadImage = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
}
// 预加载音频
preloadAudio = (url) => {
return new Promise((resolve, reject) => {
const audio = new Audio();
audio.oncanplay = a => {
resolve(audio);
};
audio.onerror = () => {
reject();
};
audio.src = url;
audio.load();
});
}
// 缓存页面元素
cartoonElementsBuffer = {}
createCartoonElement = (key, type) => {
this.cartoonElementsBuffer[key] = {
ref: null,
get boundingBox(){
return this.ref.getBoundingBox()
}
}
this.cartoonElementsBuffer[key].id = key;
switch (type) {
case "MySprite": this.cartoonElementsBuffer[key].ref = new MySprite(); break;
case "ShapeRect": this.cartoonElementsBuffer[key].ref = new ShapeRect(); break;
case "ShapeRectNew": this.cartoonElementsBuffer[key].ref = new ShapeRectNew(); break;
case "Label": this.cartoonElementsBuffer[key].ref = new Label(); break;
case "waterWave": this.cartoonElementsBuffer[key].ref = new waterWave(); break;
case "ShapeCircle": this.cartoonElementsBuffer[key].ref = new ShapeCircle(); break;
default: this.cartoonElementsBuffer[key].ref = new MySprite(); break;
}
this.cartoonElementsBuffer[key].ref.id = key;
return this.cartoonElementsBuffer[key]
}
// 创建图片
createCartoonElementImage(id: string, image: string, width: number, height: number, initX: number, initY: number, withScale?: boolean) {
let element = this.createCartoonElement(id, "MySprite")
element.ref.init(this.images.get(image))
element.initX = initX
element.initY = initY
if (withScale) {
element.initScaleX = width * this.mapScale / element.ref.width
element.initScaleY = height * this.mapScale / element.ref.height
} else {
element.initScaleX = width / element.ref.width
element.initScaleY = height / element.ref.height
}
element.ref.scaleX = element.initScaleX
element.ref.scaleY = element.initScaleY
element.ref.x = element.initX
element.ref.y = element.initY
this.attachProperties(element)
return this.cartoonElementsBuffer[id]
}
// 创建图片(回调方式)
createCartoonElementImageFunc(id: string, image: string, callbackScale: Function, callbackPosition: Function) {
let element = this.createCartoonElement(id, "MySprite")
element.ref.init(this.images.get(image))
element.rePosition = () => {
let scale = callbackScale(element.ref.width, element.ref.height)
let position = callbackPosition(element.ref.width, element.ref.height)
// save initScale
element.ref.initScaleX = scale.sx
element.ref.initScaleY = scale.sy
element.initScaleX = scale.sx
element.initScaleY = scale.sy
// save initX_Y
element.ref.initX = position.x
element.ref.initY = position.y
element.initX = position.x
element.initY = position.y
// save initRotation
element.ref.initRotation = element.rotation ? element.rotation : 0
element.initRotation = element.rotation ? element.rotation : 0
element.ref.scaleX = scale.sx
element.ref.scaleY = scale.sy
element.ref.x = element.initX
element.ref.y = element.initY
}
element.rePosition()
this.attachProperties(element)
return this.cartoonElementsBuffer[id]
}
createCartoonElementLabel(id: string, text: string, fontName?: string, fontColor?: string, fontSize?: number, initX?: number, initY?: number) {
if (!fontName) {
fontName = "BRLNSDB"
}
if (!fontColor) {
fontColor = "#000000"
}
if (!fontSize) {
fontSize = 20
}
if (!initX) {
initX = 0
}
if (!initY) {
initY = 0
}
let element = this.createCartoonElement(id, "Label")
element.ref.text = text
element.ref.fontName = fontName
element.ref.fontColor = fontColor
element.ref.fontSize = fontSize
element.ref.x = initX
element.ref.y = initY
element.initX = initX
element.initY = initY
element.initScaleX = element.ref.scaleX
element.initScaleY = element.ref.scaleY
element.ref.initScaleX = element.ref.scaleX
element.ref.initScaleY = element.ref.scaleY
element.ref.textAlign = "center"
element.ref.refreshSize();
this.attachProperties(element)
return element
}
createCartoonElementLabelFunc(id: string, text: string, fontName?: string, fontColor?: string, fontSize?: number, callback?) {
let element = this.createCartoonElement(id, "Label")
element.ref.text = text
element.ref.fontName = fontName
element.ref.fontColor = fontColor
element.ref.fontSize = fontSize
element.ref.textAlign = "center"
element.ref.refreshSize();
if (callback) {
let size = callback(element.ref.width, element.ref.height)
element.ref.x = size.x
element.ref.y = size.y
}
return element
}
createCartoonElementShapeRect(id: string, width, height, fillColor = "#FFFF00") {
let element = this.createCartoonElement(id, "ShapeRect")
element.ref.setSize(width, height);
element.ref.fillColor = fillColor;
return element
}
createLabel = (text, fontName, fontColor, fontSize, initX?, initY?, align?: string, maxWidth?: number) => {
let element = new Label()
element.text = text;
if (fontName) {
element.fontName = fontName;
}
if (fontColor) {
element.fontColor = fontColor;
}
if (fontSize) {
element.fontSize = fontSize;
}
element.refreshSize();
element.textAlign = align?align:"center";
element.x = initX;
element.y = initY;
if(maxWidth) {
let textBB = element.getBoundingBox()
if(element.width > maxWidth) {
element.scaleX = maxWidth / element.width
element.scaleY = maxWidth / element.width
}
}
return element
}
createImage(image, callbackScale, callbackPosition) {
let element = new MySprite()
element.init(this.images.get(image))
let scale = callbackScale(element.width, element.height)
let position = callbackPosition(element.width, element.height)
element.scaleX = scale.sx
element.scaleY = scale.sy
element.x = position.x
element.y = position.y
return element
}
createBorder(config) {
let element = new ShapeRectNew()
if(config.width) element.width = config.width
if(config.height) element.height = config.height
if(config.x) element.x = config.x
if(config.y) element.y =config.y
if(config.borderColor && config.lineWidth) element.setOutLine(config.borderColor, config.lineWidth)
if(config.fill){
element.fill = true
}else{
element.fill = false
}
if(config.radius) element.radius = config.radius
return element
}
createRectangula(config) {
let element = new ShapeRectNew()
element.fill = true
if(config.width) element.width = config.width
if(config.height) element.height = config.height
if(config.x) element.x = config.x
if(config.y) element.y = config.y
if(config.fillColor) element.fillColor = config.fillColor
if(config.radius) element.radius = config.radius
return element
}
createAnimation(imageKey, length, runTime, endCallback?, order?:boolean) {
let element = new MyAnimation()
element.id = "ANI-" + imageKey + "-" + Math.floor(Math.random()*10000)
if(order){
for (let index = length; index > 0; index--) {
element.addFrameByImg(this.images.get(`${imageKey} (${index})`))
}
}else{
for (let index = 0; index < length; index++) {
element.addFrameByImg(this.images.get(`${imageKey} (${index + 1})`))
}
}
element.delayPerUnit = (runTime / length) / 1000
if (element.delayPerUnit > 1) {
element.delayPerUnit = 1
} else if (element.delayPerUnit < 0.01) {
element.delayPerUnit = 0.01;
}
element.playEndFunc = () => {
endCallback && endCallback()
}
return element
}
attachProperties(cartoonElement){
// cartoonElement.updateBoundingBox = ()=>{
// cartoonElement.boundingBox = cartoonElement.ref.getBoundingBox()
// }
// cartoonElement.boundingBox = cartoonElement.ref.getBoundingBox()
}
getCartoonElementRef = (key) => {
if (this.cartoonElementsBuffer[key]) {
return this.cartoonElementsBuffer[key].ref;
} else {
return undefined
}
}
getCartoonElement = (key) => {
return this.cartoonElementsBuffer[key]
}
getCartoonElementsRef = (keys) => {
let allElelemts = []
keys.forEach(id => {
if (this.cartoonElementsBuffer[id]) {
allElelemts.push(this.cartoonElementsBuffer[id].ref)
}
});
return allElelemts
}
getCartoonElements = (keys) => {
let allElelemts = []
keys.forEach(id => {
if (this.cartoonElementsBuffer[id]) {
allElelemts.push(this.cartoonElementsBuffer[id])
}
});
return allElelemts
}
getAllCartoonElement = () => {
return this.cartoonElementsBuffer
}
setCartoonElementPosition = (key, posi) => {
this.cartoonElementsBuffer[key].ref.x = posi.x
this.cartoonElementsBuffer[key].ref.y = posi.y
this.cartoonElementsBuffer[key].x = posi.x
this.cartoonElementsBuffer[key].y = posi.y
}
setCartoonElementPositionX = (key, x) => {
this.cartoonElementsBuffer[key].ref.x = x
this.cartoonElementsBuffer[key].x = x
}
setCartoonElementRelativePositionX = (key, x) => {
this.cartoonElementsBuffer[key].relativeX = x
}
setCartoonElementPositionY = (key, y) => {
this.cartoonElementsBuffer[key].ref.y = y
this.cartoonElementsBuffer[key].y = y
}
setCartoonElementRelativePositionY = (key, y) => {
this.cartoonElementsBuffer[key].relativeY = y
}
getCartoonElementPosition = (key) => {
return {
x: this.cartoonElementsBuffer[key].x,
y: this.cartoonElementsBuffer[key].y
}
}
getCartoonElementRelativePosition = (key) => {
return {
x: this.cartoonElementsBuffer[key].relativeX,
y: this.cartoonElementsBuffer[key].relativeY
}
}
saveSize(key){
this.cartoonElementsBuffer[key].initX = this.cartoonElementsBuffer[key].ref.x
this.cartoonElementsBuffer[key].initY = this.cartoonElementsBuffer[key].ref.y
this.cartoonElementsBuffer[key].initScaleX = this.cartoonElementsBuffer[key].ref.scaleX
this.cartoonElementsBuffer[key].initScaleY = this.cartoonElementsBuffer[key].ref.scaleX
this.cartoonElementsBuffer[key].ref.initX = this.cartoonElementsBuffer[key].ref.x
this.cartoonElementsBuffer[key].ref.initY = this.cartoonElementsBuffer[key].ref.y
this.cartoonElementsBuffer[key].ref.initScaleX = this.cartoonElementsBuffer[key].ref.scaleX
this.cartoonElementsBuffer[key].ref.initScaleY = this.cartoonElementsBuffer[key].ref.scaleX
}
resetAll = () => {
this.cartoonElementsBuffer = {}
}
}
\ No newline at end of file
import TWEEN from "@tweenjs/tween.js";
import TWEEN from '@tweenjs/tween.js'; import simplexNoise from "../../assets/libs/simplex-noise/simplex-noise.min.js"
import { del } from "selenium-webdriver/http";
interface AirWindow extends Window { import construct = Reflect.construct;
air: any;
curCtx: any;
curImages: any;
}
declare let window: AirWindow;
class Sprite { class Sprite {
x = 0; x = 0;
y = 0; y = 0;
color = ''; color = "";
radius = 0; radius = 0;
alive = false; alive = false;
margin = 0; margin = 0;
angle = 0; angle = 0;
ctx; ctx;
id;
constructor(ctx = null) { constructor(ctx = null) {
if (!ctx) { if (!ctx) {
this.ctx = window.curCtx; this.ctx = window["curCtx"];
} else { } else {
this.ctx = ctx; this.ctx = ctx;
} }
...@@ -28,17 +23,10 @@ class Sprite { ...@@ -28,17 +23,10 @@ class Sprite {
update($event) { update($event) {
this.draw(); this.draw();
} }
draw() { draw() { }
}
} }
export class MySprite extends Sprite { export class MySprite extends Sprite {
_width = 0; _width = 0;
_height = 0; _height = 0;
_anchorX = 0; _anchorX = 0;
...@@ -53,14 +41,6 @@ export class MySprite extends Sprite { ...@@ -53,14 +41,6 @@ export class MySprite extends Sprite {
skewX = 0; skewX = 0;
skewY = 0; skewY = 0;
_shadowFlag = false;
_shadowColor;
_shadowOffsetX = 0;
_shadowOffsetY = 0;
_shadowBlur = 5;
_radius = 0;
children = [this]; children = [this];
childDepandVisible = true; childDepandVisible = true;
...@@ -69,209 +49,69 @@ export class MySprite extends Sprite { ...@@ -69,209 +49,69 @@ export class MySprite extends Sprite {
img; img;
_z = 0; _z = 0;
_showRect;
_bitmapFlag = false;
_offCanvas;
_offCtx;
isCircleStyle = false; // 切成圆形
parent;
_maskSpr;
init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) { init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) {
if (imgObj) { if (imgObj) {
this.img = imgObj; this.img = imgObj;
this.width = this.img.width; this.width = this.img.width;
this.height = this.img.height; this.height = this.img.height;
} }
this.anchorX = anchorX; this.anchorX = anchorX;
this.anchorY = anchorY; this.anchorY = anchorY;
} }
setShowRect(rect) {
this._showRect = rect;
}
setShadow(offX, offY, blur, color = 'rgba(0, 0, 0, 0.3)') {
this._shadowFlag = true;
this._shadowColor = color;
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
this._shadowBlur = blur;
}
setRadius(r) {
this._radius = r;
}
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');
}
}
update($event = null) { update($event = null) {
if (!this.visible && this.childDepandVisible) { if (!this.visible && this.childDepandVisible) {
return; return;
} }
this.draw(); this.draw();
} }
draw() {
draw() {
this.ctx.save(); this.ctx.save();
this.drawInit(); this.drawInit();
this.updateChildren(); this.updateChildren();
this.ctx.restore(); this.ctx.restore();
} }
drawInit() { drawInit() {
this.ctx.translate(this.x, this.y); this.ctx.translate(this.x, this.y);
this.ctx.rotate((this.rotation * Math.PI) / 180);
this.ctx.rotate(this.rotation * Math.PI / 180);
this.ctx.scale(this.scaleX, this.scaleY); this.ctx.scale(this.scaleX, this.scaleY);
this.ctx.globalAlpha = this.alpha; this.ctx.globalAlpha = this.alpha;
this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0); this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0);
} }
drawSelf() { drawSelf() {
if (this._shadowFlag) {
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
this.ctx.shadowBlur = this._shadowBlur;
this.ctx.shadowColor = this._shadowColor;
} else {
this.ctx.shadowOffsetX = 0;
this.ctx.shadowOffsetY = 0;
this.ctx.shadowBlur = null;
this.ctx.shadowColor = null;
}
if (this._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.img) {
this.ctx.drawImage(this.img, this._offX, this._offY);
if (this._showRect) {
const rect = this._showRect;
this.ctx.drawImage(this.img, rect.x, rect.y, rect.width, rect.height, this._offX + 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() { updateChildren() {
if (this.children.length <= 0) {
this._offCtx.save(); return;
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); for (let i = 0; i < this.children.length; i++) {
if (this.children[i] === this) {
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; }
for (const child of this.children) {
if (child === this) {
if (this.visible) { if (this.visible) {
this.drawSelf(); this.drawSelf();
} }
} else { } else {
child.update(); this.children[i].update();
} }
} }
} }
load(url, anchorX = 0.5, anchorY = 0.5) { load(url, anchorX = 0.5, anchorY = 0.5) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const img = new Image(); const img = new Image();
img.onload = () => resolve(img); img.onload = () => resolve(img);
img.onerror = reject; img.onerror = reject;
img.src = url; img.src = url;
}).then(img => { }).then(img => {
this.init(img, anchorX, anchorY); this.init(img, anchorX, anchorY);
return img; return img;
}); });
...@@ -288,12 +128,11 @@ export class MySprite extends Sprite { ...@@ -288,12 +128,11 @@ export class MySprite extends Sprite {
return a._z - b._z; return a._z - b._z;
}); });
if (this.childDepandAlpha) { if (this.childDepandAlpha) {
child.alpha = this.alpha; child.alpha = this.alpha;
} }
} }
removeChild(child) { removeChild(child) {
const index = this.children.indexOf(child); const index = this.children.indexOf(child);
if (index !== -1) { if (index !== -1) {
...@@ -304,29 +143,62 @@ export class MySprite extends Sprite { ...@@ -304,29 +143,62 @@ export class MySprite extends Sprite {
removeChildren() { removeChildren() {
for (let i = 0; i < this.children.length; i++) { for (let i = 0; i < this.children.length; i++) {
if (this.children[i]) { if (this.children[i]) {
if (this.children[i] !== this) { if (this.children[i] != this) {
this.children.splice(i, 1); this.children.splice(i, 1);
i --; i--;
} }
} }
} }
} }
_changeChildAlpha(alpha) { _changeChildAlpha(alpha) {
for (const child of this.children) { for (let i = 0; i < this.children.length; i++) {
if (child !== this) { if (this.children[i] != this) {
child.alpha = alpha; this.children[i].alpha = alpha;
} }
} }
} }
refreshAnchorOff() {
this._offX = -this._width * this.anchorX;
this._offY = -this._height * this.anchorY;
}
set bitmapFlag(v) { setScaleXY(value) {
this._bitmapFlag = v; this.scaleX = this.scaleY = value;
} }
get bitmapFlag() {
return this._bitmapFlag; getBoundingBox() {
const getParentData = item => {
let px = item.x;
let py = item.y;
let sx = item.scaleX;
let sy = item.scaleY;
const parent = item.parent;
if (parent) {
const obj = getParentData(parent);
const _x = obj.px;
const _y = obj.py;
const _sx = obj.sx;
const _sy = obj.sy;
px = _x + item.x * _sx;
py = _y + item.y * _sy;
sx *= _sx;
sy *= _sy;
}
return { px, py, sx, sy };
};
const data = getParentData(this);
const x = data.px + this._offX * Math.abs(data.sx);
const y = data.py + this._offY * Math.abs(data.sy);
const width = this.width * Math.abs(data.sx);
const height = this.height * Math.abs(data.sy);
return { x, y, width, height };
} }
set alpha(v) { set alpha(v) {
this._alpha = v; this._alpha = v;
if (this.childDepandAlpha) { if (this.childDepandAlpha) {
...@@ -364,88 +236,83 @@ export class MySprite extends Sprite { ...@@ -364,88 +236,83 @@ export class MySprite extends Sprite {
get anchorY() { get anchorY() {
return this._anchorY; return this._anchorY;
} }
refreshAnchorOff() { }
this._offX = -this._width * this.anchorX;
this._offY = -this._height * this.anchorY;
}
setScaleXY(value) {
this.scaleX = this.scaleY = value;
}
getBoundingBox() {
const getParentData = (item) => {
let px = item.x;
let py = item.y;
let sx = item.scaleX;
let sy = item.scaleY;
const parent = item.parent;
if (parent) {
const obj = getParentData(parent);
const _x = obj.px;
const _y = obj.py;
const _sx = obj.sx;
const _sy = obj.sy;
px = _x + item.x * _sx;
py = _y + item.y * _sy;
sx *= _sx;
sy *= _sy;
export class waterWave extends MySprite {
bottole_r = 100;
bottole_x0 = 100;
bottole_y0 = 100;
simplex = new simplexNoise()
amp = 10; //波浪幅度 可以通过函数传递参数更改不同的幅度
count = 80;
speedY = 0;
speedX = 0;
height = this.bottole_r
water_color = "red"
per = 1.5
_runTimeCtl = new Date().getTime()
draw_self(color, comp, height) {
this.ctx.beginPath();
let r = this.bottole_r
let a = this.bottole_x0 // this.bottole_r*2
let b = this.bottole_y0 // this.bottole_r*2
for (var i = 0; i <= this.count; i++) {
this.speedX += 0.05;
var x = a - r + i * (r * 2 / this.count);
var y = b + r - height + this.simplex.noise2D(this.speedX, this.speedY) * this.amp;
if (x > (a + r)) {
x = a + r
}
if (x < (a - r)) {
x = a - r
} }
return {px, py, sx, sy}; let c_y1 = Math.sqrt(r * r - (x - a) * (x - a)) + b
}; let c_y2 = -Math.sqrt(r * r - (x - a) * (x - a)) + b
if (y > c_y1) {
y = c_y1
const data = getParentData(this); }
if (y < c_y2) {
y = c_y2
const x = data.px + this._offX * Math.abs(data.sx); }
const y = data.py + this._offY * Math.abs(data.sy); this.ctx[i === 0 ? "moveTo" : "lineTo"](x, y);
const width = this.width * Math.abs(data.sx); }
const height = this.height * Math.abs(data.sy); this.ctx.arc(a, b, r, 0, Math.PI);
this.ctx.closePath();
return {x, y, width, height}; this.ctx.fillStyle = color;
this.ctx.fill();
} }
drawSelf() {
super.drawSelf();
this.speedX = 0;
if (new Date().getTime() - this._runTimeCtl > 10) {
this.speedY += 0.02; //每次渲染需要更新波峰波谷值
}
this._runTimeCtl = new Date().getTime()
this.draw_self(this.water_color, "screen", this.height);
}
} }
export class ColorSpr extends MySprite { export class ColorSpr extends MySprite {
r = 0; r = 0;
g = 0; g = 0;
b = 0; b = 0;
createGSCanvas() { createGSCanvas() {
if (!this.img) { if (!this.img) {
return; return;
} }
const rect = this.getBoundingBox(); const rect = this.getBoundingBox();
if (rect.width <= 1 || rect.height <= 1) { if (rect.width <= 1 || rect.height <= 1) {
return; return;
} }
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height); const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for ( let i = 0; i < c.height; i++) { for (let i = 0; i < c.height; i++) {
for ( let j = 0; j < c.width; j++) { for (let j = 0; j < c.width; j++) {
const x = i * 4 * c.width + j * 4;
const x = (i * 4) * c.width + ( j * 4 );
const r = c.data[x]; const r = c.data[x];
const g = c.data[x + 1]; const g = c.data[x + 1];
const b = c.data[x + 2]; const b = c.data[x + 2];
...@@ -454,88 +321,61 @@ export class ColorSpr extends MySprite { ...@@ -454,88 +321,61 @@ export class ColorSpr extends MySprite {
c.data[x + 1] = this.g; c.data[x + 1] = this.g;
c.data[x + 2] = this.b; c.data[x + 2] = this.b;
// c.data[x] = c.data[x + 1] = c.data[x + 2] = (r + g + b) / 3 ;
// // c.data[x + 3] = 255;
} }
} }
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height); this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.createGSCanvas(); this.createGSCanvas();
} }
} }
export class GrayscaleSpr extends MySprite { export class GrayscaleSpr extends MySprite {
grayScale = 120; grayScale = 120;
createGSCanvas() { createGSCanvas() {
if (!this.img) { if (!this.img) {
return; return;
} }
const rect = this.getBoundingBox(); const rect = this.getBoundingBox();
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height); const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for ( let i = 0; i < c.height; i++) { for (let i = 0; i < c.height; i++) {
for ( let j = 0; j < c.width; j++) { for (let j = 0; j < c.width; j++) {
const x = i * 4 * c.width + j * 4;
const x = (i * 4) * c.width + ( j * 4 );
const r = c.data[x]; const r = c.data[x];
const g = c.data[x + 1]; const g = c.data[x + 1];
const b = c.data[x + 2]; const b = c.data[x + 2];
// const a = c.data[x + 3];
c.data[x] = c.data[x + 1] = c.data[x + 2] = this.grayScale; // (r + g + b) / 3; c.data[x] = c.data[x + 1] = c.data[x + 2] = this.grayScale; // (r + g + b) / 3;
// c.data[x + 3] = 255;
} }
} }
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height); this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.createGSCanvas(); this.createGSCanvas();
} }
} }
export class BitMapLabel extends MySprite { export class BitMapLabel extends MySprite {
labelArr; labelArr;
baseUrl; baseUrl;
setText(data, text) { setText(data, text) {
this.labelArr = []; this.labelArr = [];
const labelArr = []; const labelArr = [];
const tmpArr = text.split(''); const tmpArr = text.split("");
let totalW = 0; let totalW = 0;
let h = 0; let h = 0;
for (const tmp of tmpArr) { for (let i = 0; i < tmpArr.length; i++) {
const label = new MySprite(this.ctx); const label = new MySprite(this.ctx);
label.init(data[tmp], 0); label.init(data[tmpArr[i]], 0);
this.addChild(label); this.addChild(label);
labelArr.push(label); labelArr.push(label);
...@@ -543,47 +383,44 @@ export class BitMapLabel extends MySprite { ...@@ -543,47 +383,44 @@ export class BitMapLabel extends MySprite {
h = label.height; h = label.height;
} }
this.width = totalW; this.width = totalW;
this.height = h; this.height = h;
let offX = -totalW / 2; let offX = -totalW / 2;
for (const label of labelArr) { for (let i = 0; i < labelArr.length; i++) {
label.x = offX; labelArr[i].x = offX;
offX += label.width; offX += labelArr[i].width;
} }
this.labelArr = labelArr; this.labelArr = labelArr;
} }
} }
export class Label extends MySprite { export class Label extends MySprite {
text: String;
text: string;
// fontSize:String = '40px'; // fontSize:String = '40px';
fontName = 'Verdana'; fontName: String = "Verdana";
textAlign = 'left'; textAlign: String = "left";
fontSize = 40; fontSize = 40;
fontColor = '#000000'; fontColor = "#000000";
fontWeight = 900; fontWeight = 900;
_maxWidth; maxWidth;
outline = 0; outline = 0;
outlineColor = '#ffffff'; outlineColor = "#ffffff";
// _shadowFlag = false; maxSingalLineWidth = 0;
// _shadowColor; baseY = 0
// _shadowOffsetX; warpLineHeight = 0;
// _shadowOffsetY; _shadowFlag = false;
// _shadowBlur; _shadowColor;
_shadowOffsetX;
_shadowOffsetY;
_shadowBlur;
_outlineFlag = false; _outlineFlag = false;
_outLineWidth; _outLineWidth;
_outLineColor; _outLineColor;
_warpLineY = 0;
constructor(ctx = null) { constructor(ctx = null) {
super(ctx); super(ctx);
...@@ -591,25 +428,45 @@ export class Label extends MySprite { ...@@ -591,25 +428,45 @@ export class Label extends MySprite {
} }
refreshSize() { refreshSize() {
this.ctx.save(); this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
this._width = this.ctx.measureText(this.text).width; this._width = this.ctx.measureText(this.text).width;
this._height = this.fontSize;
this.refreshAnchorOff();
this.ctx.restore(); let height = this.fontSize
if (this.maxSingalLineWidth !== 0) {
var words = this.text.split(' ');
var line = '';
let index = 0;
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = this.ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > this.maxSingalLineWidth && n > 0) {
// this.ctx.fillText(line, 0, this._warpLineY);
line = words[n] + ' ';
// this._warpLineY += this.fontSize;
index++
console.log(index)
height += this.fontSize;
}else {
line = testLine;
}
}
this._height = height;
}
this.refreshAnchorOff();
this.ctx.restore();
} }
setMaxSize(w) { setMaxSize(w) {
this.maxWidth = w;
this._maxWidth = w;
this.refreshSize(); this.refreshSize();
if (this.width >= w) { if (this.width >= w) {
this.scaleX *= w / this.width; this.scaleX *= w / this.width;
...@@ -618,7 +475,6 @@ export class Label extends MySprite { ...@@ -618,7 +475,6 @@ export class Label extends MySprite {
} }
show(callBack = null) { show(callBack = null) {
this.visible = true; this.visible = true;
if (this.alpha >= 1) { if (this.alpha >= 1) {
...@@ -628,7 +484,7 @@ export class Label extends MySprite { ...@@ -628,7 +484,7 @@ export class Label extends MySprite {
const tween = new TWEEN.Tween(this) const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800) .to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -636,49 +492,42 @@ export class Label extends MySprite { ...@@ -636,49 +492,42 @@ export class Label extends MySprite {
.start(); // Start the tween immediately. .start(); // Start the tween immediately.
} }
// setShadow(offX = 0, offY = 2, blur = 2, color = 'rgba(0, 0, 0, 0.2)') { setShadow(offX = 2, offY = 2, blur = 2, color = "rgba(0, 0, 0, 0.2)") {
// this._shadowFlag = true;
// this._shadowFlag = true; this._shadowColor = color;
// this._shadowColor = color; // 将阴影向右移动15px,向上移动10px
// // 将阴影向右移动15px,向上移动10px this._shadowOffsetX = offX;
// this._shadowOffsetX = 5; this._shadowOffsetY = offY;
// this._shadowOffsetY = 5; // 轻微模糊阴影
// // 轻微模糊阴影 this._shadowBlur = blur;
// this._shadowBlur = 5; }
// }
setOutline(width = 5, color = '#ffffff') {
setOutline(width = 5, color = "#ffffff") {
this._outlineFlag = true; this._outlineFlag = true;
this._outLineWidth = width; this._outLineWidth = width;
this._outLineColor = color; this._outLineColor = color;
} }
drawText() { drawText() {
// console.log('in drawText', this.text); // console.log('in drawText', this.text);
if (!this.text) { return; } if (!this.text) {
return;
}
// if (this._shadowFlag) {
//
// this.ctx.shadowColor = this._shadowColor;
// // 将阴影向右移动15px,向上移动10px
// this.ctx.shadowOffsetX = this._shadowOffsetX;
// this.ctx.shadowOffsetY = this._shadowOffsetY;
// // 轻微模糊阴影
// this.ctx.shadowBlur = this._shadowBlur;
// }
if (this._shadowFlag) {
this.ctx.shadowColor = this._shadowColor;
// 将阴影向右移动15px,向上移动10px
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
// 轻微模糊阴影
this.ctx.shadowBlur = this._shadowBlur;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
if (this._outlineFlag) { if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth; this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor; this.ctx.strokeStyle = this._outLineColor;
...@@ -687,61 +536,152 @@ export class Label extends MySprite { ...@@ -687,61 +536,152 @@ export class Label extends MySprite {
this.ctx.fillStyle = this.fontColor; this.ctx.fillStyle = this.fontColor;
if (this.outline > 0) { if (this.outline > 0) {
this.ctx.lineWidth = this.outline; this.ctx.lineWidth = this.outline;
this.ctx.strokeStyle = this.outlineColor; this.ctx.strokeStyle = this.outlineColor;
this.ctx.strokeText(this.text, 0, 0); this.ctx.strokeText(this.text, 0, 0);
}
// 当maxSingalLineWidth不为0时,对数据进行换行处理
if (this.maxSingalLineWidth !== 0) {
var words = this.text.split(' ');
var line = '';
this._warpLineY = 0;
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = this.ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > this.maxSingalLineWidth && n > 0) {
this.ctx.fillText(line, 0, this._warpLineY);
line = words[n] + ' ';
this._warpLineY += this.fontSize;
}
else {
line = testLine;
}
}
this.y = this.baseY // + this._warpLineY
this.ctx.fillText(line, 0, this._warpLineY);
} else {
this.ctx.fillText(this.text, 0, 0);
} }
}
this.ctx.fillText(this.text, 0, 0); drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class ShapeRectNew extends MySprite {
radius = 0;
fillColor = '#ffffff';
strokeColor = '#000000';
fill = true;
stroke = false;
lineWidth = 1;
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
drawShape() {
const ctx = this.ctx;
const width = this.width;
const height = this.height;
const radius = this.radius;
ctx.save();
ctx.beginPath(0);
// 从右下角顺时针绘制,弧度从0到1/2PI
ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
// 矩形下边线
ctx.lineTo(radius, height);
// 左下角圆弧,弧度从1/2PI到PI
ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
// 矩形左边线
ctx.lineTo(0, radius);
// 左上角圆弧,弧度从PI到3/2PI
ctx.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
// 上边线
ctx.lineTo(width - radius, 0);
// 右上角圆弧
ctx.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
// 右边线
ctx.lineTo(width, height - radius);
ctx.closePath();
if (this.fill) {
ctx.fillStyle = this.fillColor;
ctx.fill();
}
if (this.stroke) {
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.strokeColor;
ctx.stroke();
}
ctx.restore();
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawText(); this.drawShape();
} }
} }
export class RichTextOld extends Label { export class RichTextOld extends Label {
textArr = []; textArr = [];
fontSize = 40; fontSize = 40;
setText(text: string, words) { setText(text: string, words) {
let newText = text; let newText = text;
for (const word of words) { for (let i = 0; i < words.length; i++) {
const word = words[i];
const re = new RegExp(word, 'g'); const re = new RegExp(word, "g");
newText = newText.replace( re, `#${word}#`); newText = newText.replace(re, `#${word}#`);
// newText = newText.replace(word, `#${word}#`); // newText = newText.replace(word, `#${word}#`);
} }
this.textArr = newText.split('#'); this.textArr = newText.split("#");
this.text = newText; this.text = newText;
// this.setSize(); // this.setSize();
} }
refreshSize() { refreshSize() {
this.ctx.save(); this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
let curX = 0; let curX = 0;
for (const text of this.textArr) { for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(text).width; const w = this.ctx.measureText(this.textArr[i]).width;
curX += w; curX += w;
} }
...@@ -750,12 +690,9 @@ export class RichTextOld extends Label { ...@@ -750,12 +690,9 @@ export class RichTextOld extends Label {
this.refreshAnchorOff(); this.refreshAnchorOff();
this.ctx.restore(); this.ctx.restore();
} }
show(callBack = null) { show(callBack = null) {
// console.log(' in show '); // console.log(' in show ');
this.visible = true; this.visible = true;
// this.alpha = 0; // this.alpha = 0;
...@@ -763,186 +700,119 @@ export class RichTextOld extends Label { ...@@ -763,186 +700,119 @@ export class RichTextOld extends Label {
const tween = new TWEEN.Tween(this) const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800) .to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
}) })
.start(); // Start the tween immediately. .start(); // Start the tween immediately.
} }
drawText() { drawText() {
// console.log('in drawText', this.text); // console.log('in drawText', this.text);
if (!this.text) { return; } if (!this.text) {
return;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = 900; this.ctx.fontWeight = 900;
this.ctx.lineWidth = 5; this.ctx.lineWidth = 5;
this.ctx.strokeStyle = '#ffffff'; this.ctx.strokeStyle = "#ffffff";
// this.ctx.strokeText(this.text, 0, 0); // this.ctx.strokeText(this.text, 0, 0);
this.ctx.fillStyle = '#000000'; this.ctx.fillStyle = "#000000";
// this.ctx.fillText(this.text, 0, 0); // this.ctx.fillText(this.text, 0, 0);
let curX = 0; let curX = 0;
for (let i = 0; i < this.textArr.length; i++) { for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width; const w = this.ctx.measureText(this.textArr[i]).width;
if ((i + 1) % 2 === 0) { if ((i + 1) % 2 == 0) {
this.ctx.fillStyle = '#c8171e'; this.ctx.fillStyle = "#c8171e";
} else { } else {
this.ctx.fillStyle = '#000000'; this.ctx.fillStyle = "#000000";
} }
this.ctx.fillText(this.textArr[i], curX, 0); this.ctx.fillText(this.textArr[i], curX, 0);
curX += w; curX += w;
} }
} }
} }
export class RichText extends Label { export class RichText extends Label {
disH = 30; disH = 30;
offW = 10;
constructor(ctx?: any) { constructor(ctx = null) {
super(ctx); super(ctx);
// this.dataArr = dataArr; // this.dataArr = dataArr;
} }
drawText() { drawText() {
if (!this.text) { if (!this.text) {
return; return;
} }
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
this.ctx.fillStyle = this.fontColor; this.ctx.fillStyle = this.fontColor;
const selfW = this.width * this.scaleX; const selfW = this.width * this.scaleX;
const chr = this.text.split(" ");
const chr = this.text.split(' '); let temp = "";
let temp = '';
const row = []; const row = [];
const w = selfW - this.offW * 2; const w = selfW - 80;
const disH = (this.fontSize + this.disH) * this.scaleY; const disH = (this.fontSize + this.disH) * this.scaleY;
for (let a = 0; a < chr.length; a++) {
if (
this.ctx.measureText(temp).width < w &&
for (const c of chr) { this.ctx.measureText(temp + chr[a]).width <= w
if (this.ctx.measureText(temp).width < w && this.ctx.measureText(temp + (c)).width <= w) { ) {
temp += ' ' + c; temp += " " + chr[a];
} else { } else {
row.push(temp); row.push(temp);
temp = ' ' + c; temp = " " + chr[a];
} }
} }
row.push(temp); row.push(temp);
const x = 0; const x = 0;
const y = -row.length * disH / 2; const y = (-row.length * disH) / 2;
// for (let b = 0 ; b < row.length; b++) { // for (let b = 0 ; b < row.length; b++) {
// this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20 // this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
// } // }
if (this._outlineFlag) { if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth; this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor; this.ctx.strokeStyle = this._outLineColor;
for (let b = 0 ; b < row.length; b++) { for (let b = 0; b < row.length; b++) {
this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20 this.ctx.strokeText(row[b], x, y + (b + 1) * disH); // 每行字体y坐标间隔20
} }
// this.ctx.strokeText(this.text, 0, 0); // this.ctx.strokeText(this.text, 0, 0);
} }
// this.ctx.fillStyle = '#ff7600'; // this.ctx.fillStyle = '#ff7600';
for (let b = 0 ; b < row.length; b++) { for (let b = 0; b < row.length; b++) {
this.ctx.fillText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20 this.ctx.fillText(row[b], x, y + (b + 1) * disH); // 每行字体y坐标间隔20
} }
} }
drawSelf() {
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() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawLine(); this.drawText();
} }
} }
export class ShapeRect extends MySprite { export class ShapeRect extends MySprite {
fillColor = "#FF0000";
fillColor = '#FF0000';
setSize(w, h) { setSize(w, h) {
this.width = w; this.width = w;
...@@ -953,145 +823,79 @@ export class ShapeRect extends MySprite { ...@@ -953,145 +823,79 @@ export class ShapeRect extends MySprite {
} }
drawShape() { drawShape() {
this.ctx.fillStyle = this.fillColor; this.ctx.fillStyle = this.fillColor;
this.ctx.fillRect(this._offX, this._offY, this.width, this.height); this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawShape(); this.drawShape();
} }
} }
export class ShapeCircle extends MySprite { export class ShapeCircle extends MySprite {
fillColor = "#FFFF00";
fillColor = '#FF0000';
radius = 0; radius = 0;
startRadian = 0;
endRadian = 180;
strokeLineWidth = 5;
strokeColor = "#702dee";
drawType = "fill"
counterclockwise = false; // false 逆时针 true 顺时针
shadowColor = "rgba(0,0,0,0)"
shadowOffsetX = 0;
shadowOffsetY = 0;
setRadius(r) { setRadius(r) {
this.anchorX = this.anchorY = 0.5; this.anchorX = this.anchorY = 0.5;
this.radius = r; this.radius = r;
this.width = r * 2; this.width = r * 2;
this.height = r * 2; this.height = r * 2;
} }
drawShape() { drawShape() {
switch (this.drawType) {
this.ctx.beginPath(); case "stroke":
this.ctx.fillStyle = this.fillColor; this.ctx.beginPath();
this.ctx.arc(0, 0, this.radius, 0, angleToRadian(360)); this.ctx.strokeStyle = this.strokeColor;
this.ctx.fill(); this.ctx.lineWidth = this.strokeLineWidth
} this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian, this.counterclockwise);
this.ctx.stroke()
drawSelf() { break;
super.drawSelf(); default:
this.drawShape(); this.ctx.beginPath();
} this.ctx.fillStyle = this.fillColor;
} this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian);
this.ctx.shadowColor = this.shadowColor
export class ShapeRectNew extends MySprite { this.ctx.shadowOffsetX = this.shadowOffsetX
this.ctx.shadowOffsetY = this.shadowOffsetY
this.ctx.fill();
radius = 0; break;
fillColor = '#ffffff';
strokeColor = '#000000';
fill = true;
stroke = false;
lineWidth = 1;
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
drawShape() {
const ctx = this.ctx;
const width = this.width;
const height = this.height;
const radius = this.radius;
ctx.save();
ctx.beginPath(0);
// 从右下角顺时针绘制,弧度从0到1/2PI
ctx.arc(width - radius + 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();
} }
ctx.restore();
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawShape(); this.drawShape();
} }
} }
export class MyAnimation extends MySprite {
export class MyAnimation extends MySprite {
frameArr = []; frameArr = [];
frameIndex = 0; frameIndex = 0;
playFlag = false; playFlag = false;
lastDateTime; lastDateTime;
curDelay = 0; curDelay = 0;
loop = false; loop = false;
playEndFunc; playEndFunc;
delayPerUnit = 0.07; delayPerUnit = 1;
restartFlag = false; restartFlag = false;
reverseFlag = false; reverseFlag = false;
addFrameByImg(img) { addFrameByImg(img) {
const spr = new MySprite(this.ctx); const spr = new MySprite(this.ctx);
spr.init(img); spr.init(img);
this._refreshSize(img); this._refreshSize(img);
...@@ -1105,10 +909,8 @@ export class MyAnimation extends MySprite { ...@@ -1105,10 +909,8 @@ export class MyAnimation extends MySprite {
} }
addFrameByUrl(url) { addFrameByUrl(url) {
const spr = new MySprite(this.ctx); const spr = new MySprite(this.ctx);
spr.load(url).then(img => { spr.load(url).then(img => {
this._refreshSize(img); this._refreshSize(img);
}); });
spr.visible = false; spr.visible = false;
...@@ -1119,18 +921,15 @@ export class MyAnimation extends MySprite { ...@@ -1119,18 +921,15 @@ export class MyAnimation extends MySprite {
this.frameArr[this.frameIndex].visible = true; this.frameArr[this.frameIndex].visible = true;
} }
_refreshSize(img: any) { _refreshSize(img) {
if (this.width < img["width"]) {
if (this.width < img.width) { this.width = img["width"];
this.width = img.width;
} }
if (this.height < img.height) { if (this.height < img["height"]) {
this.height = img.height; this.height = img["height"];
} }
} }
play() { play() {
this.playFlag = true; this.playFlag = true;
this.lastDateTime = new Date().getTime(); this.lastDateTime = new Date().getTime();
...@@ -1140,13 +939,11 @@ export class MyAnimation extends MySprite { ...@@ -1140,13 +939,11 @@ export class MyAnimation extends MySprite {
this.playFlag = false; this.playFlag = false;
} }
replay() { replay() {
this.restartFlag = true; this.restartFlag = true;
this.play(); this.play();
} }
reverse() { reverse() {
this.reverseFlag = !this.reverseFlag; this.reverseFlag = !this.reverseFlag;
this.frameArr.reverse(); this.frameArr.reverse();
...@@ -1154,29 +951,26 @@ export class MyAnimation extends MySprite { ...@@ -1154,29 +951,26 @@ export class MyAnimation extends MySprite {
} }
showAllFrame() { showAllFrame() {
for (const frame of this.frameArr ) { for (let i = 0; i < this.frameArr.length; i++) {
frame.alpha = 1; this.frameArr[i].alpha = 1;
} }
} }
hideAllFrame() { hideAllFrame() {
for (const frame of this.frameArr) { for (let i = 0; i < this.frameArr.length; i++) {
frame.alpha = 0; this.frameArr[i].alpha = 0;
} }
} }
playEnd() { playEnd() {
this.playFlag = false; this.playFlag = false;
this.curDelay = 0; this.curDelay = 0;
this.frameArr[this.frameIndex].visible = true; this.frameArr[this.frameIndex].visible = true;
if (this.playEndFunc) { if (this.playEndFunc) {
const func = this.playEndFunc; this.playEndFunc();
this.playEndFunc = null; this.playEndFunc = null;
func();
} }
} }
...@@ -1185,7 +979,7 @@ export class MyAnimation extends MySprite { ...@@ -1185,7 +979,7 @@ export class MyAnimation extends MySprite {
this.frameArr[this.frameIndex].visible = false; this.frameArr[this.frameIndex].visible = false;
} }
this.frameIndex ++; this.frameIndex++;
if (this.frameIndex >= this.frameArr.length) { if (this.frameIndex >= this.frameArr.length) {
if (this.loop) { if (this.loop) {
this.frameIndex = 0; this.frameIndex = 0;
...@@ -1193,21 +987,16 @@ export class MyAnimation extends MySprite { ...@@ -1193,21 +987,16 @@ export class MyAnimation extends MySprite {
this.restartFlag = false; this.restartFlag = false;
this.frameIndex = 0; this.frameIndex = 0;
} else { } else {
this.frameIndex -- ; this.frameIndex--;
this.playEnd(); this.playEnd();
return; return;
} }
} }
this.frameArr[this.frameIndex].visible = true; this.frameArr[this.frameIndex].visible = true;
} }
_updateDelay(delay) { _updateDelay(delay) {
this.curDelay += delay; this.curDelay += delay;
if (this.curDelay < this.delayPerUnit) { if (this.curDelay < this.delayPerUnit) {
return; return;
...@@ -1217,7 +1006,9 @@ export class MyAnimation extends MySprite { ...@@ -1217,7 +1006,9 @@ export class MyAnimation extends MySprite {
} }
_updateLastDate() { _updateLastDate() {
if (!this.playFlag) { return; } if (!this.playFlag) {
return;
}
let delay = 0; let delay = 0;
if (this.lastDateTime) { if (this.lastDateTime) {
...@@ -1231,26 +1022,18 @@ export class MyAnimation extends MySprite { ...@@ -1231,26 +1022,18 @@ export class MyAnimation extends MySprite {
super.update($event); super.update($event);
this._updateLastDate(); this._updateLastDate();
} }
} }
// --------=========== util func =============------------- // --------=========== util func =============-------------
export function tweenChange(
export function tweenChange(item, obj, time = 0.8, callBack = null, easing = null, update = null) { item,
obj,
const tween = createTween(item, obj, time, callBack, easing, update) time = 0.8,
tween.start(); callBack = null,
easing = null,
return tween; update = null
} ) {
export function createTween(item, obj, time = 0.8, callBack = null, easing = null, update = null) {
const tween = new TWEEN.Tween(item).to(obj, time * 1000); const tween = new TWEEN.Tween(item).to(obj, time * 1000);
if (callBack) { if (callBack) {
...@@ -1262,47 +1045,29 @@ export function createTween(item, obj, time = 0.8, callBack = null, easing = nul ...@@ -1262,47 +1045,29 @@ export function createTween(item, obj, time = 0.8, callBack = null, easing = nul
tween.easing(easing); tween.easing(easing);
} }
if (update) { if (update) {
tween.onUpdate( (a, b) => { tween.onUpdate((a, b) => {
update(a, b); update(a, b);
}); });
} }
return tween;
}
export function tweenQueue(arr) {
const showOneTween = () => { tween.start();
const tween = arr.shift(); return tween;
if (arr.length > 0) {
tween.onComplete( () => {
showOneTween();
});
}
tween.start();
};
showOneTween();
} }
export function rotateItem(
item,
rotation,
export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = null, loop = false) { time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000); const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000);
if (callBack) { if (callBack) {
tween.onComplete(() => { tween.onComplete(() => {
callBack(); 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) { if (easing) {
tween.easing(easing); tween.easing(easing);
} }
...@@ -1310,11 +1075,17 @@ export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = ...@@ -1310,11 +1075,17 @@ export function rotateItem(item, rotation, time = 0.8, callBack = null, easing =
tween.start(); tween.start();
} }
export function scaleItem(
item,
export function scaleItem(item, scale, time = 0.8, callBack = null, easing = null) { scale,
time = 0.8,
const tween = new TWEEN.Tween(item).to({ scaleX: scale, scaleY: scale}, time * 1000); callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to(
{ scaleX: scale, scaleY: scale },
time * 1000
);
if (callBack) { if (callBack) {
tween.onComplete(() => { tween.onComplete(() => {
...@@ -1329,10 +1100,15 @@ export function scaleItem(item, scale, time = 0.8, callBack = null, easing = nul ...@@ -1329,10 +1100,15 @@ export function scaleItem(item, scale, time = 0.8, callBack = null, easing = nul
return tween; return tween;
} }
export function moveItem(
export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) { item,
x,
const tween = new TWEEN.Tween(item).to({ x, y}, time * 1000); y,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to({ x, y }, time * 1000);
if (callBack) { if (callBack) {
tween.onComplete(() => { tween.onComplete(() => {
...@@ -1348,36 +1124,26 @@ export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) ...@@ -1348,36 +1124,26 @@ export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null)
return tween; return tween;
} }
export function endShow(item, s = 1) { export function endShow(item, s = 1) {
item.scaleX = item.scaleY = 0; item.scaleX = item.scaleY = 0;
item.alpha = 0; item.alpha = 0;
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({ alpha: 1, scaleX: s, scaleY: s }, 800) .to({ alpha: 1, scaleX: s, scaleY: s }, 800)
.easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth. .easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () { })
})
.start(); .start();
} }
export function hideItem(item, time = 0.8, callBack = null, easing = null) { export function hideItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha == 0) {
if (item.alpha === 0) {
return; return;
} }
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha: 0}, time * 1000) .to({ alpha: 0 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1390,10 +1156,8 @@ export function hideItem(item, time = 0.8, callBack = null, easing = null) { ...@@ -1390,10 +1156,8 @@ export function hideItem(item, time = 0.8, callBack = null, easing = null) {
tween.start(); tween.start();
} }
export function showItem(item, time = 0.8, callBack = null, easing = null) { export function showItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha == 1) {
if (item.alpha === 1) {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1402,9 +1166,9 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) { ...@@ -1402,9 +1166,9 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) {
item.visible = true; item.visible = true;
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha: 1}, time * 1000) .to({ alpha: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1417,14 +1181,17 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) { ...@@ -1417,14 +1181,17 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) {
tween.start(); tween.start();
} }
export function alphaItem(
export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = null) { item,
alpha,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha}, time * 1000) .to({ alpha: alpha }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1437,14 +1204,11 @@ export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = nul ...@@ -1437,14 +1204,11 @@ export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = nul
tween.start(); tween.start();
} }
export function showStar(item, time = 0.8, callBack = null, easing = null) { export function showStar(item, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha: 1, scale: 1}, time * 1000) .to({ alpha: 1, scale: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function () {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1457,97 +1221,103 @@ export function showStar(item, time = 0.8, callBack = null, easing = null) { ...@@ -1457,97 +1221,103 @@ export function showStar(item, time = 0.8, callBack = null, easing = null) {
tween.start(); tween.start();
} }
export function randomSortByArr(arr) { export function randomSortByArr(arr) {
const newArr = []; const newArr = [];
const tmpArr = arr.concat(); const tmpArr = arr.concat();
while (tmpArr.length > 0) { while (tmpArr.length > 0) {
const randomIndex = Math.floor( tmpArr.length * Math.random() ); const randomIndex = Math.floor(tmpArr.length * Math.random());
newArr.push(tmpArr[randomIndex]); newArr.push(tmpArr[randomIndex]);
tmpArr.splice(randomIndex, 1); tmpArr.splice(randomIndex, 1);
} }
return newArr; return newArr;
} }
export function radianToAngle(radian) { export function radianToAngle(radian) {
return radian * 180 / Math.PI; return (radian * 180) / Math.PI;
// 角度 = 弧度 * 180 / Math.PI; // 角度 = 弧度 * 180 / Math.PI;
} }
export function angleToRadian(angle) { export function angleToRadian(angle) {
return angle * Math.PI / 180; return (angle * Math.PI) / 180;
// 弧度= 角度 * Math.PI / 180; // 弧度= 角度 * Math.PI / 180;
} }
export function getPosByAngle(angle, len) { export function getPosByAngle(angle, len) {
const radian = (angle * Math.PI) / 180;
const radian = angle * Math.PI / 180;
const x = Math.sin(radian) * len; const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len; const y = Math.cos(radian) * len;
return {x, y}; return { x, y };
} }
export function getAngleByPos(px, py, mx, my) { export function getAngleByPos(px, py, mx, my) {
const x = Math.abs(px - mx); const x = Math.abs(px - mx);
const y = Math.abs(py - my); const y = Math.abs(py - my);
const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
const cos = y / z; const cos = y / z;
const radina = Math.acos(cos); // 用反三角函数求弧度 const radina = Math.acos(cos); // 用反三角函数求弧度
let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度 let angle = Math.floor((180 / (Math.PI / radina)) * 100) / 100; // 将弧度转换成角度
if (mx > px && my > py) {// 鼠标在第四象限 if (mx > px && my > py) {
// 鼠标在第四象限
angle = 180 - angle; angle = 180 - angle;
} }
if (mx === px && my > py) {// 鼠标在y轴负方向上 if (mx === px && my > py) {
// 鼠标在y轴负方向上
angle = 180; angle = 180;
} }
if (mx > px && my === py) {// 鼠标在x轴正方向上 if (mx > px && my === py) {
// 鼠标在x轴正方向上
angle = 90; angle = 90;
} }
if (mx < px && my > py) {// 鼠标在第三象限 if (mx < px && my > py) {
// 鼠标在第三象限
angle = 180 + angle; angle = 180 + angle;
} }
if (mx < px && my === py) {// 鼠标在x轴负方向 if (mx < px && my === py) {
// 鼠标在x轴负方向
angle = 270; angle = 270;
} }
if (mx < px && my < py) {// 鼠标在第二象限 if (mx < px && my < py) {
// 鼠标在第二象限
angle = 360 - angle; angle = 360 - angle;
} }
// console.log('angle: ', angle); // console.log('angle: ', angle);
return angle; return angle;
} }
export function removeItemFromArr(arr, item) { export function removeItemFromArr(arr, item) {
const index = arr.indexOf(item); const index = arr.indexOf(item);
if (index !== -1) { if (index != -1) {
arr.splice(index, 1); arr.splice(index, 1);
} }
} }
export function circleMove(
item,
x0,
y0,
time = 2,
export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = 1, callBack = null, easing = null) { addR = 360,
xPer = 1,
yPer = 1,
callBack = null,
easing = null
) {
const r = getPosDistance(item.x, item.y, x0, y0); const r = getPosDistance(item.x, item.y, x0, y0);
let a = getAngleByPos(item.x, item.y, x0, y0); let a = getAngleByPos(item.x, item.y, x0, y0);
a += 90; a += 90;
const obj = {r, a}; const obj = { r, a };
item._circleAngle = a; item._circleAngle = a;
const targetA = a + addR; const targetA = a + addR;
const tween = new TWEEN.Tween(item).to({_circleAngle: targetA}, time * 1000); const tween = new TWEEN.Tween(item).to(
{ _circleAngle: targetA },
time * 1000
);
if (callBack) { if (callBack) {
tween.onComplete(() => { tween.onComplete(() => {
...@@ -1558,14 +1328,13 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = ...@@ -1558,14 +1328,13 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer =
tween.easing(easing); tween.easing(easing);
} }
tween.onUpdate( (item, progress) => { tween.onUpdate((item, progress) => {
// console.log(item._circleAngle); // console.log(item._circleAngle);
const r = obj.r; const r = obj.r;
const a = item._circleAngle; const a = item._circleAngle;
const x = x0 + r * xPer * Math.cos(a * Math.PI / 180); const x = x0 + r * xPer * Math.cos((a * Math.PI) / 180);
const y = y0 + r * yPer * Math.sin(a * Math.PI / 180); const y = y0 + r * yPer * Math.sin((a * Math.PI) / 180);
item.x = x; item.x = x;
item.y = y; item.y = y;
...@@ -1576,16 +1345,14 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = ...@@ -1576,16 +1345,14 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer =
tween.start(); tween.start();
} }
export function getPosDistance(sx, sy, ex, ey) { export function getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx; const _x = ex - sx;
const _y = ey - sy; const _y = ey - sy;
const len = Math.sqrt( Math.pow(_x, 2) + Math.pow(_y, 2) ); const len = Math.sqrt(Math.pow(_x, 2) + Math.pow(_y, 2));
return len; return len;
} }
export function delayCall(second, callback) { export function delayCall(callback, second) {
const tween = new TWEEN.Tween(this) const tween = new TWEEN.Tween(this)
.delay(second * 1000) .delay(second * 1000)
.onComplete(() => { .onComplete(() => {
...@@ -1596,46 +1363,14 @@ export function delayCall(second, callback) { ...@@ -1596,46 +1363,14 @@ export function delayCall(second, callback) {
.start(); .start();
} }
export function getMinScale(item, maxLen) {
export function formatTime(fmt, date) { const sx = maxLen / item.width;
const sy = maxLen / item.height;
// "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;
const minS = Math.min(sx, sy); const minS = Math.min(sx, sy);
return minS; return minS;
} }
export function jelly(item, time = 0.7) { export function jelly(item, time = 0.7) {
if (item.jellyTween) { if (item.jellyTween) {
TWEEN.remove(item.jellyTween); TWEEN.remove(item.jellyTween);
} }
...@@ -1651,10 +1386,16 @@ export function jelly(item, time = 0.7) { ...@@ -1651,10 +1386,16 @@ export function jelly(item, time = 0.7) {
return; return;
} }
const data = arr[index]; const data = arr[index];
const t = tweenChange(item, {scaleX: data[0], scaleY: data[1]}, data[2], () => { const t = tweenChange(
index ++; item,
run(); { scaleX: data[0], scaleY: data[1] },
}, TWEEN.Easing.Sinusoidal.InOut); data[2],
() => {
index++;
run();
},
TWEEN.Easing.Sinusoidal.InOut
);
item.jellyTween = t; item.jellyTween = t;
}; };
...@@ -1663,60 +1404,24 @@ export function jelly(item, time = 0.7) { ...@@ -1663,60 +1404,24 @@ export function jelly(item, time = 0.7) {
[baseSX * 0.98, baseSY * 1.02, t * 2], [baseSX * 0.98, baseSY * 1.02, t * 2],
[baseSX * 1.02, baseSY * 0.98, t * 2], [baseSX * 1.02, baseSY * 0.98, t * 2],
[baseSX * 0.99, baseSY * 1.01, t * 2], [baseSX * 0.99, baseSY * 1.01, t * 2],
[baseSX * 1.0, baseSY * 1.0, t * 2], [baseSX * 1.0, baseSY * 1.0, t * 2]
];
run();
}
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 ++;
run();
}, TWEEN.Easing.Sinusoidal.InOut);
item.jellyTween = t;
};
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],
]; ];
item.setScaleXY(0);
run(); run();
} }
/**
* 烟花爆炸效果动画
export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen = 80, showTime = 0.4) { * @param img 颗粒的图片
* @param pos 爆点的坐标
* @param parent 必须传一个父类
for (let i = 0; i < num; i ++) { */
export function showPopParticle(img, pos, parent) {
const num = 20;
const maxLen = 100;
const minLen = 40;
for (let i = 0; i < num; i++) {
const particle = new MySprite(); const particle = new MySprite();
particle.init(img); particle.init(img);
particle.x = pos.x; particle.x = pos.x;
...@@ -1726,8 +1431,8 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen ...@@ -1726,8 +1431,8 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen
const randomR = 360 * Math.random(); const randomR = 360 * Math.random();
particle.rotation = randomR; particle.rotation = randomR;
const randomS = 0.3 + Math.random() * 0.7; const randomS = 0.5 + Math.random() * 0.5;
particle.setScaleXY(randomS * 0.3); particle.setScaleXY(randomS);
const randomX = Math.random() * 20 - 10; const randomX = Math.random() * 20 - 10;
particle.x += randomX; particle.x += randomX;
...@@ -1735,39 +1440,23 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen ...@@ -1735,39 +1440,23 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen
const randomY = Math.random() * 20 - 10; const randomY = Math.random() * 20 - 10;
particle.y += randomY; particle.y += randomY;
const randomL = minLen + Math.random() * (maxLen - minLen); const randomL = minLen + Math.random() * maxLen;
const randomA = 360 * Math.random(); const randomA = 360 * Math.random();
const randomT = getPosByAngle(randomA, randomL); const randomT = getPosByAngle(randomA, randomL);
moveItem(particle, particle.x + randomT.x, particle.y + randomT.y, showTime, () => { moveItem(
particle,
particle.x + randomT.x,
particle.y + randomT.y,
}, TWEEN.Easing.Exponential.Out); 0.4,
() => { },
// scaleItem(particle, 0, 0.6, () => { TWEEN.Easing.Exponential.Out
// );
// });
scaleItem(particle, randomS, 0.6, () => {
}, TWEEN.Easing.Exponential.Out);
setTimeout(() => {
hideItem(particle, 0.4, () => {
}, TWEEN.Easing.Cubic.In);
}, showTime * 0.5 * 1000);
scaleItem(particle, 0, 0.6, () => { });
} }
} }
export function shake(item, time = 0.5, callback = null, rate = 1) { export function shake(item, time = 0.5, callback = null, rate = 1) {
if (item.shakeTween) { if (item.shakeTween) {
return; return;
} }
...@@ -1779,73 +1468,104 @@ export function shake(item, time = 0.5, callback = null, rate = 1) { ...@@ -1779,73 +1468,104 @@ export function shake(item, time = 0.5, callback = null, rate = 1) {
const baseY = item.y; const baseY = item.y;
const easing = TWEEN.Easing.Sinusoidal.InOut; const easing = TWEEN.Easing.Sinusoidal.InOut;
const move4 = () => { const move4 = () => {
moveItem(item, baseX, baseY, time / 4, () => { moveItem(
item.shakeTween = false; item,
if (callback) { baseX,
callback(); baseY,
} time / 4,
}, easing); () => {
item.shakeTween = false;
if (callback) {
callback();
}
},
easing
);
}; };
const move3 = () => { const move3 = () => {
moveItem(item, baseX + offX / 4, baseY + offY / 4, time / 4, () => { moveItem(
move4(); item,
}, easing); baseX + offX / 4,
baseY + offY / 4,
time / 4,
() => {
move4();
},
easing
);
}; };
const move2 = () => { const move2 = () => {
moveItem(item, baseX - offX / 4 * 3, baseY - offY / 4 * 3, time / 4, () => { moveItem(
move3(); item,
}, easing); baseX - (offX / 4) * 3,
baseY - (offY / 4) * 3,
time / 4,
() => {
move3();
},
easing
);
}; };
const move1 = () => { const move1 = () => {
moveItem(item, baseX + offX, baseY + offY, time / 7.5, () => { moveItem(
move2(); item,
}, easing); baseX + offX,
baseY + offY,
time / 8,
() => {
move2();
},
easing
);
}; };
move1(); move1();
} }
export function getMaxScale(item, maxW, maxH) { // --------------- custom class --------------------
const sx = maxW / item.width; export function showBlingBling(starImg, rectArea, parent, mapScale = 1, num = 30, disTime = 0.1, showTime = 3) {
const sy = maxH / item.height; const timeId = setInterval(() => {
const maxS = Math.max(sx, sy); showBlingStar(starImg, num, rectArea, parent, mapScale);
return maxS; }, disTime * 1000);
} setTimeout(() => {
clearInterval(timeId);
}, showTime * 1000);
export function createSprite(key) {
const image = window.curImages;
const spr = new MySprite();
spr.init(image.get(key));
return spr;
} }
export class MyVideo extends MySprite { function showBlingStar(starImg, num, rectArea, parent, mapScale) {
element; for (let i = 0; i < num; i++) {
const star = new MySprite();
star.init(starImg);
initVideoElement(videoElement) { const px = -parent.width / 2 + Math.random() * parent.width;
const py = -parent.height / 2 + Math.random() * parent.height;
star.x = px;
star.y = py;
this.element = videoElement; const randomS = (0.1 + Math.random() * 0.8) * mapScale;
this.width = this.element.videoWidth; star.setScaleXY(1);
this.height = this.element.videoHeight;
this.element.currentTime = 0.01; parent.addChild(star);
}
drawSelf() { scaleItem(star, randomS, 0.3, () => {
super.drawSelf();
this.ctx.drawImage(this.element, 0, 0, this.width, this.height); setTimeout(() => {
}
}
scaleItem(star, 0, 0.3, () => {
parent.removeChild(star);
});
}, 100 + Math.random() * 200);
});
}
// --------------- custom class --------------------
}
\ No newline at end of file
.game-container {
width: 100%;
height: 100%;
background: #ffffff;
background-size: cover;
}
#canvas {
}
@font-face
{
font-family: 'BRLNSDB';
src: url("../../assets/font/BRLNSDB.TTF") ;
}
.game-container {
width: 100%;
height: 100%;
//background-image: url("/assets/play/listen-read-circle/bg.jpg");
background: #ffffff;
background-repeat: no-repeat;
background-size: cover;
}
.read-and-point-copy {
width: 500px;
height: 85px;
object-fit: contain;
text-shadow: 0 6px 4px rgba(0, 0, 0, 0.5), 0 3px 0 #fffecc;
font-family: Questrian;
font-size: 72px;
font-weight: normal;
font-stretch: normal;
font-style: normal;
line-height: normal;
letter-spacing: normal;
color: #f8e424;
}
.read-and-point-copy .text-style-1 {
font-size: 48px;
}
.read-and-point-copy .text-style-2 {
font-size: 64px;
}
// @font-face{
// font-family: 'BRLNSDB';
// src: url("../../assets/default/font/BRLNSDB.TTF") ;
// }
// @font-face{
// font-family: 'RoundedBold';
// src: url("../../assets/default/font/ArialRoundedBold.otf") ;
// }
// @font-face{
// font-family: 'BRLNSB_1';
// src: url("../../assets/default/font/BerlinSansFB/BRLNSB_1.TTF") ;
// }
// @font-face{
// font-family: 'BerlinSansFBDemi-Bold';
// src: url("../../assets/default/font/BerlinSansFB/BRLNSDB_1.TTF") ;
// }
// @font-face{
// font-family: 'BRLNSR_1';
// src: url("../../assets/default/font/BerlinSansFB/BRLNSR_1.TTF") ;
// }
// @font-face{
// font-family: 'GOTHIC_1';
// src: url("../../assets/default/font/CenturyGothic/GOTHIC_1.TTF") ;
// }
// @font-face{
// font-family: 'GOTHICB_1';
// src: url("../../assets/default/font/CenturyGothic/GOTHICB_1.TTF") ;
// }
// @font-face{
// font-family: 'GOTHICBI_1';
// src: url("../../assets/default/font/CenturyGothic/GOTHICBI_1.TTF") ;
// }
// @font-face{
// font-family: 'GOTHICI_1';
// src: url("../../assets/default/font/CenturyGothic/GOTHICI_1.TTF") ;
// }
// @font-face{
// font-family: 'MMTextBook';
// src: url("../../assets/default/font/MMTextBook/MMTextBook.otf") ;
// }
// @font-face{
// font-family: 'MMTextBook-Bold';
// src: url("../../assets/default/font/MMTextBook/MMTextBook-Bold.otf") ;
// }
// @font-face{
// font-family: 'MMTextBook-BoldItalic';
// src: url("../../assets/default/font/MMTextBook/MMTextBook-BoldItalic.otf") ;
// }
// @font-face{
// font-family: 'MMTextBook-Italic';
// src: url("../../assets/default/font/MMTextBook/MMTextBook-Italic.otf") ;
// }
// @font-face{
// font-family: 'tt0142m';
// src: url("../../assets/play/font/tt0142m.ttf") ;
// }
@font-face{
font-family: 'Aileron-Black';
src: url("../../assets/play/font/Aileron-Black.ttf") ;
}
@font-face{
font-family: 'Aileron-Bold';
src: url("../../assets/play/font/Aileron-Bold.ttf") ;
}
@font-face{
font-family: 'DroidSansFallback';
src: url("../../assets/play/font/DroidSansFallback.ttf") ;
}
// @font-face{
// font-family: 'FuturaStd-Medium';
// src: url("../../assets/play/font/FuturaStd-Medium.otf") ;
// }
// @font-face{
// font-family: 'FuturaBT-Bold';
// src: url("../../assets/play/font/FuturaBT-Bold.otf") ;
// }
// @font-face{
// font-family: 'GOTHICB_1';
// src: url("../../assets/play/font/GOTHICB_1.ttf") ;
// }
import {Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener} from '@angular/core'; import {
Component,
ElementRef,
ViewChild,
OnInit,
Input,
OnDestroy,
HostListener
} from "@angular/core";
import { import {
MySprite,
RichText,
getMinScale,
ShapeRect,
ShapeCircle,
tweenChange,
randomSortByArr,
Label, Label,
MySprite, tweenChange, showPopParticle,
moveItem,
removeItemFromArr,
rotateItem,
hideItem,
showItem,
ShapeRectNew,
scaleItem,
showBlingBling,
waterWave,
jelly,
getAngleByPos,
getPosDistance,
shake
} from "./Unit";
import { localImages, localAudios, multiSizeBackground} from "./resources";
import { Cartoon } from './Cartoon'
import { Subject } from "rxjs";
import { debounceTime, map, takeWhile, retry } from "rxjs/operators";
import * as _ from "lodash";
import TWEEN from "@tweenjs/tween.js";
import { demoData as defaultData } from '../../assets/default/formData/DataKey_JM04_3.js'
const zIndexMap = {
mainBackground: 0,
zhangyu: 100,
button: 110,
popup: 105
}
} from './Unit'; @Component({
import {res, resAudio} from './resources'; selector: "app-play",
templateUrl: "./play.component.html",
styleUrls: ["./play.component.scss"]
})
import {Subject} from 'rxjs'; export class PlayComponent implements OnInit, OnDestroy {
import {debounceTime} from 'rxjs/operators';
g_cartoon = new Cartoon()
// ------------ 全局数据 ------------
g_topElementContainer; // 用于装载装饰元素 气球 星星等
g_stage; //中心舞台
// g_background_color = "#rgb(0,0,0,0)"
g_background_color = "#FFFFFF"
g_enableMapDown = true; // 触摸使能
g_enableMapUp = true; // 抬起使能
g_enableMapMove = true; // 移动ss使能
g_canvasLeft;
g_canvasTop;
g_animationId: any;
g_mapScale = 1; // 缩放比例
g_KEY = "DataKey_JM04_3";
g_canvasWidth = 2388;
g_canvasHeight = 1688;
g_canvasBaseW = 2388;
g_canvasBaseH = 1688;
g_winResizeEventStream = new Subject();
g_clickX; // 点击坐标 X
g_clickY; // 点击坐标 Y
g_ctx; // canvas 实例
g_data; // 数据
g_formData; // 核心表单数据
g_teacherFlag = false; // 默认角色
g_currentUser;
g_firstTouch = true;
g_partTitle_x = null;
g_mainTitle_x = null;
// ------------------------------------
// ------------ 私有数据 ------------
m_mapDownQueue = {} //按下事件处理队列
m_mapDownArray = [] //按下事件处理队列
m_mapDownObject = []
m_mapUpQueue = {} //抬起事件处理队列
m_mapUpArray = [] //抬起事件处理队列
m_mapUpObject = []
m_mapDragQueue = {} //拖拽事件处理队列
m_mapDragArray = [] //拖拽事件处理队列
m_mapDragObject = []
m_mapMoveArray = [] //移动事件处理队列
m_mapMoveObject = []
m_endPageArr;
m_showPetalFlag;
m_elementPetalArr;
m_showElementPetalFlag;
m_PetalImage = "_scrap-pic-" // 飘落动画
m_renderArr // 渲染队列
m_renderObject = [];
m_frontCurtainArr = []; // 前置幕布
m_defaultZindex = 0;
m_setTimeoutIDs = [];
m_setIntervalIDs = [];
m_moveAsstantIntervalId = null;
g_currentDragElementID: any = null; // 当前拖动的动画元件
g_dragFirstClickY: any;
g_dragFirstClickX: any;
g_enableDragDistance: number = 20 * this.g_mapScale;
g_enableDragging: any;
g_maskLayerZindex = 100;
// ------------------------------------
// ------------ 游戏逻辑数据 ------------
// ------------------------------------
// ------------ 消息 ------------
// ------------------------------------
// ------------ 调试变量 ------------
g_EnableStageRuler = false; // 使能舞台背景格尺
g_ForceChangeDefaultRole = false // 强制当前角色为默认角色
g_EnableTestSendEvent = false // 发送模拟Web数据
g_showLeftCornerTest= false // 测试左上角图标
// ------------------------------------
// 当数据加载完毕后,执行
systemReady(){
this.setLeftCornerTest()
this.initGame()
}
// 屏幕尺寸变化后执行
handleScreenResize(){
this.cleanSystemVar()
this.cleanGameVar();
this.setLeftCornerTest();
this.disableMoveAsstant();
this.initSystem();
this.initGame()
}
import TWEEN from '@tweenjs/tween.js'; // 映射预加载图片[网路]资源 返回包含图片路径的数组
mapToImageArray(contentObj){
let array = []
return array
}
// 映射预加载音频[网路]资源 返回包含音频路径的数组
mapToAduioArray(contentObj){
let array = []
// contentObj.long_audio.audio_url && array.push(contentObj.long_audio.audio_url)
return array
}
// ------------------------------------------------------------------------------
// 游戏核心处理区
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
//
//
//
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
initGame(){
console.log(this.g_formData);
this.initBackground();
this.initTitle();
this.initQuestion()
}
cleanGameVar(){
@Component({ }
selector: 'app-play',
templateUrl: './play.component.html',
styleUrls: ['./play.component.css']
})
export class PlayComponent implements OnInit, OnDestroy {
@ViewChild('canvas', {static: true }) canvas: ElementRef; startGame(){
@ViewChild('wrap', {static: true }) wrap: ElementRef;
// 数据 }
data;
ctx; restartGame(){
// this.cleanGameVar()
this.startGame()
}
canvasWidth = 1280; // canvas实际宽度 initBackground() {
canvasHeight = 720; // canvas实际高度 let color = this.g_cartoon.createCartoonElementShapeRect("background_color", this.g_canvasWidth, this.g_canvasHeight, "#fefdf9");
color.ref.x =0;
color.ref.y = 0;
this.render(color.ref)
canvasBaseW = 1280; // canvas 资源预设宽度 let mask = this.g_cartoon.createCartoonElementImageFunc("background_mask", "bg_main_mask", (w, h)=>{
canvasBaseH = 720; // canvas 资源预设高度 return {
sx: this.g_canvasWidth / 2 / w,
sy: this.g_canvasHeight / h,
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 2 + this.g_canvasWidth / 4,
y: this.g_canvasHeight / 2
}
})
this.render(mask.ref)
}
mx; // 点击x坐标 initTitle() {
my; // 点击y坐标 let text = this.g_cartoon.createCartoonElementLabelFunc("main-title", this.g_formData.title.mainText, "Aileron-Black", "#000000", 76, (w, h)=>{
return {
x: 160 * this.g_mapScale + w * this.g_mapScale / 2,
y: 65 * this.g_mapScale,
}
})
text.ref.fontWeight = 900
text.ref.fontColor = "#3e9b31"
text.ref.setScaleXY(this.g_mapScale);
this.render(text.ref)
}
// 资源 initQuestion() {
rawImages = new Map(res); let element = this.g_cartoon.createCartoonElementImageFunc("question_container", "bg_question", (w, h)=>{
rawAudios = new Map(resAudio); return {
sx: 2408*this.g_mapScale / w,
sy: 240*this.g_mapScale / h,
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 2,
y: 247 * this.g_mapScale + (240*this.g_mapScale) / 2
}
})
images = new Map(); let btnNext = this.g_cartoon.createCartoonElementImageFunc("question_next", "btn_next", (w, h)=>{
return {
sx: 136 / w,
sy: 136 / h,
}
}, (w, h)=>{
return {
x: 1010,
y: 0
}
})
animationId: any; let btnPre = this.g_cartoon.createCartoonElementImageFunc("question_pre", "btn_pre", (w, h)=>{
winResizeEventStream = new Subject(); return {
sx: 136 / w,
sy: 136 / h,
}
}, (w, h)=>{
return {
x: -1010,
y: 0
}
})
let labelIndex = this.g_cartoon.createCartoonElementLabelFunc("question_index", "", "Aileron-Bold", "#3e9b31", 48, (w, h)=>{
return {
x: 0,
y: -110,
}
})
labelIndex.ref.text = "Across 1"
audioObj = {}; let questionText = this.g_cartoon.createCartoonElementLabelFunc("question_text", "", "DroidSansFallback", "#FFFFFF", 64, (w, h)=>{
return {
x: 0,
y: 10,
}
})
questionText.ref.text = "a fish whose head look like those of a horse"
renderArr;
mapScale = 1;
canvasLeft; element.ref.addChild(labelIndex.ref)
canvasTop; element.ref.addChild(questionText.ref)
element.ref.addChild(btnNext.ref)
element.ref.addChild(btnPre .ref)
this.render(element.ref)
}
saveKey = 'test_0011'; initTitle_Part(){
let element = this.g_cartoon.createCartoonElementImageFunc("part-title", "bg_title_part", (w, h)=>{
return {
sx: 57*this.g_mapScale / w,
sy: 65*this.g_mapScale / h,
}
}, (w, h)=>{
return {
x: 53*this.g_mapScale + (57*this.g_mapScale)/2,
y: (65*this.g_mapScale)/2
}
})
element.ref.x = this.g_partTitle_x - 20 * this.g_mapScale + (57*this.g_mapScale)/2;
let text = this.g_cartoon.createLabel(this.g_formData.title.NO?this.g_formData.title.NO:"C", "Berlin Sans FB Demi Bold", "#facf46", 48)
element.ref.addChild(text)
let partBG = this.g_cartoon.createCartoonElementImageFunc("part-title-background", "part_number_bg", (w, h)=>{
return {
sx: 121*this.g_mapScale / w,
sy: 69*this.g_mapScale / h,
}
}, (w, h)=>{
return {
x: (121*this.g_mapScale)/2,
y: (69*this.g_mapScale)/2
}
})
this.render(partBG.ref)
this.render(element.ref)
}
btnLeft; initTitle_Main(){
btnRight; let labelWidth = 0
pic1; let text = this.g_cartoon.createCartoonElementLabelFunc("main-title", this.g_formData.title.mainText, "FuturaBT Medium", "#000000", 36, (w, h)=>{
pic2; labelWidth = w/2
return {
x: this.g_partTitle_x - 20 * this.g_mapScale + labelWidth * this.g_mapScale,
y: 5*this.g_mapScale + (65*this.g_mapScale) / 2
}
})
text.ref.fontWeight = 900
text.ref.setScaleXY(this.g_mapScale)
let background = this.g_cartoon.createCartoonElementImageFunc("main-title-background", "_bg_50_20", (w, h)=>{
return {
sx: labelWidth*2 / w,
sy: 50*this.g_mapScale / h,
}
}, (w, h)=>{
return {
x: this.g_partTitle_x + labelWidth + 60 * this.g_mapScale,
y: 5*this.g_mapScale + (65*this.g_mapScale) / 2
}
})
canTouch = true; text.ref.x = this.g_partTitle_x + 60 * this.g_mapScale
text.ref.textAlign = "left"
curPic; this.subscribeMapDownEvent(background.id, ()=>{
this.g_cartoon.stopAllAudio()
this.g_cartoon.playAudio(this.g_formData.title.mainTextAudio_url);
this.resetLongAudio();
this.g_enableMapDown = true;
})
@HostListener('window:resize', ['$event']) this.render(background.ref)
onResize(event) { this.render(text.ref)
this.winResizeEventStream.next();
} }
initCards() {
let cardContainer = this.g_cartoon.createCartoonElementImageFunc(`background_card_container`, "_bg_1280_720", (w, h)=>{
return {
sx: 1280*this.g_mapScale * 0.94 / w,
sy: 720*this.g_mapScale * 0.94 / h,
}
}, (w, h)=>{
return {
x: this.g_canvasWidth / 2,
y: this.g_canvasHeight / 2
}
})
this.render(cardContainer.ref)
const len = this.g_formData.dataArray.length<=4?"4":"6";
const pos = {
"4": {
cards: [
{x: -270, y: -142}, {x: 270, y: -142}, {x: -270, y: 142}, {x: 270, y: 142}
],
icon: {x: -230, y: -105},
textMain: {x: 0, y: -72},
textLeft: {x: -140, y: 82},
textRight: {x: 140, y: 82},
targetLeft: {x: -260, y: 10},
targetRight: {x: 0, y: 10},
radioLeft: {x: -140, y: 10},
radioRight: {x: 140, y: 10},
circleSize: {w: 316, h: 292},
circleLeft: {x: -80, y: 0},
circleRight: {x: 80, y: 0}
},
"6": {
cards: [
{x: -270, y: -185}, {x: 270, y: -185}, {x: -270, y: 0}, {x: 270, y: 0}, {x: -270, y: 185}, {x: 270, y: 185}
],
icon: {x: -230, y: -60},
textMain: {x: 0, y: -40},
textLeft: {x: -140, y: 72},
textRight: {x: 140, y: 72},
targetLeft: {x: -260, y: 0},
targetRight: {x: 0, y: 0},
radioLeft: {x: -140, y: 20},
radioRight: {x: 140, y: 20},
circleSize: {w: 300, h: 220},
circleLeft: {x: -80, y: 0},
circleRight: {x: 80, y: 0}
}
}
this.g_formData.dataArray.forEach((dataItem, i) => {
let bgCard = null
if(len=="4") {
bgCard = this.g_cartoon.createCartoonElementImageFunc(`background_card_${i}`, `bg_card_4_${i+1}`, (w, h)=>{
return {
sx: 520 / w,
sy: 267 / h,
}
}, (w, h)=>{
return pos[len].cards[i]
})
} else {
bgCard = this.g_cartoon.createCartoonElementImageFunc(`background_card_${i}`, `bg_card_6_${i+1}`, (w, h)=>{
return {
sx: 520 / w,
sy: 168 / h,
}
}, (w, h)=>{
return pos[len].cards[i]
})
}
ngOnInit() { let numIcon = this.g_cartoon.createCartoonElementImageFunc(`card_${i}_numIcon`, `num_icon_${i+1}`, (w, h)=>{
return {
sx: 60 / w,
sy: 60 / h,
}
}, (w, h)=>{
return pos[len].icon
})
bgCard.ref.addChild(numIcon.ref)
let textMainContainer = this.g_cartoon.createCartoonElementShapeRect(`popup-text-back-main-${i}-container`, 386, 100, "#FFFF00");
bgCard.ref.addChild(textMainContainer.ref);
textMainContainer.ref.alpha = 0;
let baseX = 0;
for(let wi=0; wi<dataItem.letters_main.length; wi++) {
let letter = this.g_cartoon.createLabel(dataItem.letters_main[wi].letter_val, "Century Gothic Bold", dataItem.letters_main[wi].letter_color, 48 * 1, baseX, 50, "left")
let bd = letter.getBoundingBox();
baseX += bd.width + 1
textMainContainer.ref.addChild(letter)
}
textMainContainer.ref.width = baseX;
textMainContainer.ref.x = - (pos[len].textMain.x + baseX) / 2;
textMainContainer.ref.y = pos[len].textMain.y - 50;
let textLeftContainer = this.g_cartoon.createCartoonElementShapeRect(`popup-text-back-left-${i}-container`, 386, 100, "#FFFF00");
let lettersSpecLeft = []
let lettersLeft = []
bgCard.ref.addChild(textLeftContainer.ref);
textLeftContainer.ref.alpha = 0;
baseX = 0;
for(let wi=0; wi<dataItem.letters_left.length; wi++) {
let letter = this.g_cartoon.createLabel(dataItem.letters_left[wi].letter_val, "FuturaBT-Bold", "#363333", 42 * 1, baseX, 50, "left")
let bd = letter.getBoundingBox();
baseX += bd.width + 1
textLeftContainer.ref.addChild(letter);
if(dataItem.letters_left[wi].letter_color=="#c8161e") {
lettersSpecLeft.push(letter)
}
lettersLeft.push(letter)
}
textLeftContainer.ref.width = baseX;
textLeftContainer.ref.x = pos[len].textLeft.x - baseX / 2;
textLeftContainer.ref.y = pos[len].textLeft.y - 50;
let textRightContainer = this.g_cartoon.createCartoonElementShapeRect(`popup-text-back-right-${i}-container`, 386, 100, "#FFFF00");
let lettersSpecRight = []
let lettersRight = [];
bgCard.ref.addChild(textRightContainer.ref);
textRightContainer.ref.alpha = 0;
baseX = 0;
for(let wi=0; wi<dataItem.letters_right.length; wi++) {
let letter = this.g_cartoon.createLabel(dataItem.letters_right[wi].letter_val, "FuturaBT-Bold", "#363333", 42 * 1, baseX, 50, "left")
let bd = letter.getBoundingBox();
baseX += bd.width + 1
textRightContainer.ref.addChild(letter)
if(dataItem.letters_right[wi].letter_color=="#c8161e") {
lettersSpecRight.push(letter)
}
lettersRight.push(letter)
}
textRightContainer.ref.width = baseX;
textRightContainer.ref.x = pos[len].textRight.x - baseX / 2;
textRightContainer.ref.y = pos[len].textRight.y - 50;
// let textLeft = this.g_cartoon.createLabel(dataItem.text_left, "FuturaBT-Bold", "#363333", 42, pos[len].textLeft.x, pos[len].textLeft.y, null, 225)
// bgCard.ref.addChild(textLeft)
// let textRight = this.g_cartoon.createLabel(dataItem.text_right, "FuturaBT-Bold", "#363333", 42, pos[len].textRight.x, pos[len].textRight.y, null, 225)
// bgCard.ref.addChild(textRight)
let targetLeft = this.g_cartoon.createCartoonElementShapeRect(`card_${i}_target_left`, 260, 110, "#FFFF00")
targetLeft.ref.x = pos[len].targetLeft.x;
targetLeft.ref.y = pos[len].targetLeft.y;
bgCard.ref.addChild(targetLeft.ref)
targetLeft.ref.alpha = 0;
let targetRight = this.g_cartoon.createCartoonElementShapeRect(`card_${i}_target_right`, 260, 110, "#FFFF00")
targetRight.ref.x = pos[len].targetRight.x;
targetRight.ref.y = pos[len].targetRight.y;
bgCard.ref.addChild(targetRight.ref)
targetRight.ref.alpha = 0;
let radioButtonLeft_out = this.g_cartoon.createCartoonElementImageFunc(`card_${i}_radio_left`, "radio_out", (w, h)=>{
return {
sx: 38 / w,
sy: 38 / h,
}
}, (w, h)=>{
return pos[len].radioLeft
})
bgCard.ref.addChild(radioButtonLeft_out.ref)
let radioButtonLeft_inner = this.g_cartoon.createCartoonElementImageFunc(`card_${i}_radio_left_inner`, "radio_inner", (w, h)=>{
return {
sx: 20 / w,
sy: 20 / h,
}
}, (w, h)=>{
return {x: 0, y: 0}
})
radioButtonLeft_out.ref.addChild(radioButtonLeft_inner.ref)
let radioButtonRight_out = this.g_cartoon.createCartoonElementImageFunc(`card_${i}_radio_right`, "radio_out", (w, h)=>{
return {
sx: 38 / w,
sy: 38 / h,
}
}, (w, h)=>{
return pos[len].radioRight
})
bgCard.ref.addChild(radioButtonRight_out.ref)
let radioButtonRight_inner = this.g_cartoon.createCartoonElementImageFunc(`card_${i}_radio_right_inner`, "radio_inner", (w, h)=>{
return {
sx: 20 / w,
sy: 20 / h,
}
}, (w, h)=>{
return {x: 0, y: 0}
})
radioButtonRight_out.ref.addChild(radioButtonRight_inner.ref)
let circleLeft = this.g_cartoon.createCartoonElementImageFunc(`card_${i}_circle_left`, "circle_l", (w, h)=>{
return {
sx: pos[len].circleSize.w / w,
sy: pos[len].circleSize.h / h,
}
}, (w, h)=>{
return pos[len].circleLeft
})
bgCard.ref.addChild(circleLeft.ref)
circleLeft.ref.alpha = 0;
let circleRight = this.g_cartoon.createCartoonElementImageFunc(`card_${i}_circle_right`, "circle_r", (w, h)=>{
return {
sx: pos[len].circleSize.w / w,
sy: pos[len].circleSize.h / h,
}
}, (w, h)=>{
return pos[len].circleRight
})
bgCard.ref.addChild(circleRight.ref)
circleRight.ref.alpha = 0;
radioButtonLeft_inner.ref.alpha = 0;
radioButtonRight_inner.ref.alpha = 0;
bgCard.switchSelect = (type) => {
switch(type) {
case "left":
radioButtonLeft_inner.ref.alpha = 255;
radioButtonRight_inner.ref.alpha = 0;
break;
case "right":
radioButtonLeft_inner.ref.alpha = 0;
radioButtonRight_inner.ref.alpha = 255;
break;
default:
radioButtonLeft_inner.ref.alpha = 0;
radioButtonRight_inner.ref.alpha = 0;
}
}
this.data = {}; this.subscribeMapDownEvent(textMainContainer.id, ()=>{
if(dataItem.audio_url_main) {
this.g_cartoon.playAudio(dataItem.audio_url_main, false, ()=>{
this.g_enableMapDown = true;
})
} else {
this.g_enableMapDown = true;
}
})
this.subscribeMapDownEvent(textLeftContainer.id, ()=>{
if(dataItem.audio_url_left) {
this.g_cartoon.playAudio(dataItem.audio_url_left, false, ()=>{
this.g_enableMapDown = true;
})
} else {
this.g_enableMapDown = true;
}
})
this.subscribeMapDownEvent(textRightContainer.id, ()=>{
if(dataItem.audio_url_right) {
this.g_cartoon.playAudio(dataItem.audio_url_right, false, ()=>{
this.g_enableMapDown = true;
})
} else {
this.g_enableMapDown = true;
}
})
bgCard.selected = false;
this.subscribeMapDownEvent(radioButtonRight_out.id, ()=>{
if(!bgCard.selected) {
bgCard.switchSelect("right")
if(dataItem.rightSide == "right") {
this.g_cartoon.playAudio("sm-correct", false, ()=>{
this.g_enableMapDown = true;
})
circleRight.ref.alpha = 255;
lettersSpecRight.forEach(le=>{
le.fontColor = "#c8161e"
})
lettersRight.forEach(le=>{
le.fontSize = 48
})
bgCard.selected = true;
} else {
this.g_cartoon.playAudio("sm-wrong", false, ()=>{
this.g_enableMapDown = true;
})
}
} else {
this.g_enableMapDown = true;
}
})
this.subscribeMapDownEvent(radioButtonLeft_out.id, ()=>{
if(!bgCard.selected) {
bgCard.switchSelect("left")
if(dataItem.rightSide == "left") {
this.g_cartoon.playAudio("sm-correct", false, ()=>{
this.g_enableMapDown = true;
})
circleLeft.ref.alpha = 255;
lettersSpecLeft.forEach(le=>{
le.fontColor = "#c8161e"
})
lettersLeft.forEach(le=>{
le.fontSize = 48
})
bgCard.selected = true;
} else {
this.g_cartoon.playAudio("sm-wrong", false, ()=>{
this.g_enableMapDown = true;
})
}
} else {
this.g_enableMapDown = true;
}
})
cardContainer.ref.addChild(bgCard.ref)
});
}
// 获取数据
const getData = (<any> window).courseware.getData;
getData((data) => {
if (data && typeof data == 'object') { initAudioPlayerAll(){
this.data = data; let element = this.g_cartoon.createCartoonElementImageFunc(`audio-all`, "icon_audio_container", (w, h)=>{
return {
sx: 76 * this.g_mapScale / w,
sy: 77 * this.g_mapScale / h,
}
}, (w, h)=>{
return {
x: this.g_canvasWidth - 66 * this.g_mapScale,
y: this.g_canvasHeight - 50 * this.g_mapScale,
} }
// console.log('data:' , data); })
element.ref.setScaleXY(0)
// 初始化 各事件监听 let play = this.g_cartoon.createCartoonElementImageFunc(`audio-all-play`, "icon_paly", (w, h)=>{
this.initListener(); return {
sx: 76 / w,
sy: 77 / h,
}
}, (w, h)=>{
return {
x: 0,
y: 0
}
})
// 若无数据 则为预览模式 需要填充一些默认数据用来显示 let pause = this.g_cartoon.createCartoonElementImageFunc(`audio-all-pause`, "icon_pause", (w, h)=>{
this.initDefaultData(); return {
sx: 76 / w,
sy: 77 / h,
}
}, (w, h)=>{
return {
x: 0,
y: 0
}
})
pause.ref.visible = false;
element.playIcon = play
element.pauseIcon = pause
element.ref.addChild(element.playIcon.ref)
element.ref.addChild(element.pauseIcon.ref)
element.isPlaying = false
element.audio = this.g_cartoon.audio.get(this.g_formData.long_audio.audio_url)
if(element.audio){
element.audio.onended = ()=>{
element.pause()
}
}
element.play = ()=>{
if(!element.audio){
return
}
element.isPlaying = true;
this.g_cartoon.stopAllAudio()
element.audio.play()
element.playIcon.ref.visible = false;
element.pauseIcon.ref.visible = true;
}
// 初始化 音频资源 element.pause = ()=>{
this.initAudio(); if(!element.audio){
// 初始化 图片资源 return
this.initImg(); }
// 开始预加载资源 element.isPlaying = false;
this.load(); element.audio.pause()
element.playIcon.ref.visible = true;
element.pauseIcon.ref.visible = false;
}
}, this.saveKey); element.enable = false
element.out = ()=>{
element.enable = true;
tweenChange(element.ref, {scaleX: element.initScaleX, scaleY: element.initScaleY}, 0.2, ()=>{
this.showJellyAnimation(element.id)
})
}
} this.subscribeMapDownEvent(element.id, ()=>{
if(!element.audio || !element.enable){
this.g_enableMapDown = true;
return
}
if(element.isPlaying){
element.pause()
}else{
element.play()
}
this.g_enableMapDown = true;
})
ngOnDestroy() { if(this.g_formData.long_audio.audio_url) {
window['curCtx'] = null; element.out()
window.cancelAnimationFrame(this.animationId); }
this.cleanAudio(); this.render(element.ref, 99)
} }
resetLongAudio(){
cleanAudio() { let audio = this.g_cartoon.getCartoonElement(`audio-all`)
if (this.audioObj) { if(audio.enable){
for (const key in this.audioObj) { audio.pause()
this.audioObj[key].pause();
}
} }
} }
load() {
// 预加载资源
this.loadResources().then(() => {
window["air"].hideAirClassLoading(this.saveKey, this.data);
this.init();
this.update();
});
// --------------------------------------------------
// -------------- Template function ---------------
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
//
// _________
// / /.
// .-------------. /_________/ |
// / / | | | |
// /+============+\ | | |====| | |
// ||C:\> || | | | |
// || || | | |====| | |
// || || | | ___ | |
// || || | | |166| | |
// || ||/@@@ | --- | |
// \+============+/ @ |_________|./.
// @ .. ....'
// ..................@ __.'.' ''
// /oooooooooooooooo// ///
// /................// /_/
// ------------------
//
// --------------------------------------------------
@ViewChild('canvas', {static: true }) canvas: ElementRef;
@ViewChild('wrap', {static: true }) wrap: ElementRef;
@HostListener("window:resize", ["$event"])
onResize(event) {
this.g_winResizeEventStream.next();
} }
ngOnDestroy() {
window["curCtx"] = null;
this.g_cartoon.stopAllAudio()
window.cancelAnimationFrame(this.g_animationId);
}
ngOnInit() {
const getData = (<any>window).courseware.getData;
getData(data => {
// if (window['air'].airClassInfo.user.classRole == 'tea') {
// if(!this.g_ForceChangeDefaultRole){
// this.g_teacherFlag = true;
// }
// }
// this.g_currentUser = window['air'].airClassInfo.user;
if (data && typeof data == "object") {
this.g_data = data;
this.g_formData = data.contentObj;
} else {
this.g_data = {};
}
if (!this.g_data.contentObj) {
this.g_data.contentObj = {};
this.g_formData = {};
}
init() { this.initDefaultData();
this.initAudio();
this.initImg();
// 预加载资源
this.g_cartoon.loadResources().then(() => {
window["air"].hideAirClassLoading(this.g_KEY, this.g_data);
this.initSystem();
this.update();
this.systemReady()
});
this.initCtx(); this.initListener();
this.initData(); }, this.g_KEY);
this.initView();
} }
initCtx() { // ----------------------------------
this.canvasWidth = this.wrap.nativeElement.clientWidth; // 初始化默认数据
this.canvasHeight = this.wrap.nativeElement.clientHeight; // ----------------------------------
this.canvas.nativeElement.width = this.wrap.nativeElement.clientWidth; initDefaultData() {
this.canvas.nativeElement.height = this.wrap.nativeElement.clientHeight; if ( Object.keys(this.g_formData).length===0 || this.g_formData.version != defaultData.version ) {
this.g_formData = defaultData;
console.log("Use default data.", this.g_formData)
}
}
this.ctx = this.canvas.nativeElement.getContext('2d'); // ----------------------------------
this.canvas.nativeElement.width = this.canvasWidth; // 初始化音乐
this.canvas.nativeElement.height = this.canvasHeight; // ----------------------------------
initAudio() {
const contentObj = this.g_formData;
if (!contentObj) {
return;
}
// 添加用户上传音效
let images:Array<string> = this.mapToAduioArray(contentObj)
images.forEach(image => {
this.g_cartoon.addAudio( image, image );
});
window['curCtx'] = this.ctx; // 添加本地音效
window['curImages'] = this.images; for( var key in localAudios ){
this.g_cartoon.addAudio( key, localAudios[key] );
}
} }
// ----------------------------------
// 初始化图片
// ----------------------------------
initImg() {
const contentObj = this.g_formData;
if (contentObj) {
const addPicUrl = url => {
if (url) {
this.g_cartoon.addImage(url, url);
}
};
let images:Array<string> = this.mapToImageArray(contentObj)
images.forEach(image => {
addPicUrl(image)
});
}
// 添加本地图片
for( var key in localImages ){
this.g_cartoon.addImage( key, localImages[key] );
}
}
mapDown(event) {
let myStopPropagation = false;
if (!this.g_enableMapDown) {
return;
}
this.m_mapDownArray.forEach((item)=>{
if(!myStopPropagation){
if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(item.id))) {
this.g_enableMapDown = false;
if(this.m_mapDragObject[item.id]){
this.m_mapDragObject[item.id].trigger()
let dragElement = this.g_cartoon.getCartoonElement(item.id)
if(dragElement){
this.g_currentDragElementID = item.id
this.g_dragFirstClickX = this.g_clickX
this.g_dragFirstClickY = this.g_clickY
this.enableMoveAsstant(()=>{
this.m_mapDragObject[item.id].move(dragElement)
})
}
myStopPropagation = true;
}else{
if(item.callback()){
myStopPropagation = true;
}
}
}
}
})
}
mapMove(event) {
let myStopPropagation = false;
if (!this.g_enableMapMove) {
return;
}
this.m_mapMoveArray.forEach((item)=>{
if(!myStopPropagation){
if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(item.id))) {
this.g_enableMapMove = false;
if(item.callback()){
myStopPropagation = true;
}
}
}
})
}
mapUp(event) {
let myStopPropagation = false;
if (!this.g_enableMapUp) {
return;
}
this.m_mapUpArray.forEach((item)=>{
if(!myStopPropagation){
if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(item.id))) {
this.g_enableMapUp = false;
if(item.callback()){
myStopPropagation = true;
}
this.g_currentDragElementID = null;
this.disableMoveAsstant();
}
}
})
}
update() {
this.g_animationId = window.requestAnimationFrame(this.update.bind(this));
// 清除画布内容
this.g_ctx.clearRect(0, 0, this.g_canvasWidth, this.g_canvasHeight);
TWEEN.update();
this.updateArr(this.m_renderArr);
this.updateArr(this.m_endPageArr);
this.updateArr(this.m_elementPetalArr);
this.updateArr(this.m_frontCurtainArr)
}
updateItem(item) { updateItem(item) {
if (item) { if (item) {
...@@ -174,50 +1062,39 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -174,50 +1062,39 @@ export class PlayComponent implements OnInit, OnDestroy {
} }
} }
initListener() { initListener() {
const element = this.canvas.nativeElement;
this.winResizeEventStream this.g_winResizeEventStream.pipe(debounceTime(500)).subscribe(data => {
.pipe(debounceTime(500)) this.renderAfterResize();
.subscribe(data => { });
this.renderAfterResize();
}); const addTouchListener = () => {
element.addEventListener('touchstart', touchDownFunc);
element.addEventListener('touchmove', touchMoveFunc);
// --------------------------------------------- element.addEventListener('touchend', touchUpFunc);
const setParentOffset = () => { element.addEventListener('touchcancel', touchUpFunc);
const rect = this.canvas.nativeElement.getBoundingClientRect();
this.canvasLeft = rect.left;
this.canvasTop = rect.top;
}; };
const setMxMyByTouch = (event) => { const removeTouchListener = () => {
if (event.touches.length <= 0) { element.removeEventListener('touchstart', touchDownFunc);
return; element.removeEventListener('touchmove', touchMoveFunc);
} element.removeEventListener('touchend', touchUpFunc);
if (this.canvasLeft == null) { element.removeEventListener('touchcancel', touchUpFunc);
setParentOffset();
}
this.mx = event.touches[0].pageX - this.canvasLeft;
this.my = event.touches[0].pageY - this.canvasTop;
}; };
const setMxMyByMouse = (event) => { const addMouseListener = () => {
this.mx = event.offsetX; element.addEventListener('mousedown', mouseDownFunc);
this.my = event.offsetY; element.addEventListener('mousemove', mouseMoveFunc);
element.addEventListener('mouseup', mouseUpFunc);
};
const removeMouseListener = () => {
element.removeEventListener('mousedown', mouseDownFunc);
element.removeEventListener('mousemove', mouseMoveFunc);
element.removeEventListener('mouseup', mouseUpFunc);
}; };
// ---------------------------------------------
let firstTouch = true;
const touchDownFunc = (e) => { const touchDownFunc = (e) => {
if (firstTouch) { if (this.g_firstTouch) {
firstTouch = false; this.g_firstTouch = false;
removeMouseListener(); removeMouseListener();
} }
setMxMyByTouch(e); setMxMyByTouch(e);
...@@ -233,8 +1110,8 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -233,8 +1110,8 @@ export class PlayComponent implements OnInit, OnDestroy {
}; };
const mouseDownFunc = (e) => { const mouseDownFunc = (e) => {
if (firstTouch) { if (this.g_firstTouch) {
firstTouch = false; this.g_firstTouch = false;
removeTouchListener(); removeTouchListener();
} }
setMxMyByMouse(e); setMxMyByMouse(e);
...@@ -249,135 +1126,85 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -249,135 +1126,85 @@ export class PlayComponent implements OnInit, OnDestroy {
this.mapUp(e); this.mapUp(e);
}; };
const setMxMyByTouch = event => {
const element = this.canvas.nativeElement; if (event.touches.length <= 0) {
return;
const addTouchListener = () => { }
element.addEventListener('touchstart', touchDownFunc); if (this.g_canvasLeft == null) {
element.addEventListener('touchmove', touchMoveFunc); setParentOffset();
element.addEventListener('touchend', touchUpFunc); }
element.addEventListener('touchcancel', touchUpFunc); this.g_clickX = event.touches[0].pageX - this.g_canvasLeft;
}; this.g_clickY = event.touches[0].pageY - this.g_canvasTop;
const removeTouchListener = () => {
element.removeEventListener('touchstart', touchDownFunc);
element.removeEventListener('touchmove', touchMoveFunc);
element.removeEventListener('touchend', touchUpFunc);
element.removeEventListener('touchcancel', touchUpFunc);
}; };
const addMouseListener = () => { const setParentOffset = () => {
element.addEventListener('mousedown', mouseDownFunc); const rect = this.canvas.nativeElement.getBoundingClientRect();
element.addEventListener('mousemove', mouseMoveFunc); this.g_canvasLeft = rect.left;
element.addEventListener('mouseup', mouseUpFunc); this.g_canvasTop = rect.top;
}; };
const removeMouseListener = () => {
element.removeEventListener('mousedown', mouseDownFunc); const setMxMyByMouse = (event) => {
element.removeEventListener('mousemove', mouseMoveFunc); this.g_clickX = event.offsetX;
element.removeEventListener('mouseup', mouseUpFunc); this.g_clickY = event.offsetY;
}; };
addMouseListener(); addMouseListener();
addTouchListener(); addTouchListener();
} }
showArr(arr) {
playAudio(key, now = false, callback = null) { if (!arr) {
return;
const audio = this.audioObj[key]; }
if (audio) { for (let i = 0; i < arr.length; i++) {
if (now) { arr[i].visible = true;
audio.pause();
audio.currentTime = 0;
}
if (callback) {
audio.onended = () => {
callback();
};
}
audio.play();
} }
} }
hideArr(arr) {
if (!arr) {
loadResources() { return;
const pr = []; }
this.rawImages.forEach((value, key) => {// 预加载图片 for (let i = 0; i < arr.length; i++) {
arr[i].visible = false;
const p = this.preload(value) }
.then(img => {
this.images.set(key, img);
})
.catch(err => console.log(err));
pr.push(p);
});
this.rawAudios.forEach((value, key) => {// 预加载音频
const a = this.preloadAudio(value)
.then(() => {
// this.images.set(key, img);
})
.catch(err => console.log(err));
pr.push(a);
});
return Promise.all(pr);
}
preload(url) {
return new Promise((resolve, reject) => {
const img = new Image();
// img.crossOrigin = "anonymous";
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
} }
preloadAudio(url) { IsPC() {
return new Promise((resolve, reject) => { if (window["ELECTRON"]) {
const audio = new Audio(); return false; // 封装客户端标记
audio.oncanplay = (a) => { }
resolve(); if (
}; document.body.ontouchmove !== undefined &&
audio.onerror = () => { document.body.ontouchmove !== undefined
reject(); ) {
}; return false;
audio.src = url; } else {
audio.load(); return true;
}); }
} }
renderAfterResize() { renderAfterResize() {
this.canvasWidth = this.wrap.nativeElement.clientWidth; this.g_canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight; this.g_canvasHeight = this.wrap.nativeElement.clientHeight;
this.init(); this.update();
this.handleScreenResize()
} }
checkClickTarget(target) { checkClickTarget(target) {
if (!target) {
return false;
}
const rect = target.getBoundingBox(); const rect = target.getBoundingBox();
if (this.checkPointInRect(this.g_clickX, this.g_clickY, rect)) {
if (this.checkPointInRect(this.mx, this.my, rect)) {
return true; return true;
} }
return false; return false;
} }
getWorlRect(target) { getWorlRect(target) {
let rect = target.getBoundingBox(); let rect = target.getBoundingBox();
if (target.parent) { if (target.parent) {
const pRect = this.getWorlRect(target.parent); const pRect = this.getWorlRect(target.parent);
rect.x += pRect.x; rect.x += pRect.x;
rect.y += pRect.y; rect.y += pRect.y;
...@@ -394,297 +1221,772 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -394,297 +1221,772 @@ export class PlayComponent implements OnInit, OnDestroy {
return false; return false;
} }
getPosByAngle(angle, len) {
const radian = (angle * Math.PI) / 180;
const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len;
return { x, y };
}
getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx;
const _y = ey - sy;
const len = Math.sqrt(Math.pow(_x, 2) + Math.pow(_y, 2));
return len;
}
subscribeMapDownEvent(id,callback, zIndex?){
zIndex = zIndex?zIndex:0
this.m_mapDownObject.push({id:id, zIndex:zIndex?zIndex:1, callback:callback})
this.m_mapDownObject.sort((a,b)=>{
return b.zIndex-a.zIndex
})
this.m_mapDownArray = []
this.m_mapDownObject.forEach(item=>{
this.m_mapDownArray.push(item)
})
}
subscribeMapUpEvent(id,callback, zIndex?){
zIndex = zIndex?zIndex:0
this.m_mapUpObject.push({id:id, zIndex:zIndex?zIndex:1, callback:callback})
this.m_mapUpObject.sort((a,b)=>{
return b.zIndex-a.zIndex
})
this.m_mapUpArray = []
this.m_mapUpObject.forEach(item=>{
this.m_mapUpArray.push(item)
})
}
addUrlToAudioObj(key, url = null, vlomue = 1, loop = false, callback = null) { subscribeMapMoveEvent(id, callback, zIndex?){
zIndex = zIndex?zIndex:0
this.m_mapMoveObject.push({id:id, zIndex:zIndex?zIndex:1, callback:callback})
this.m_mapMoveObject.sort((a,b)=>{
return a.zIndex - b.zIndex
})
this.m_mapMoveArray = []
this.m_mapMoveObject.forEach(item=>{
this.m_mapMoveArray.push(item)
})
}
const audioObj = this.audioObj; subscribeMapDragEvent(id, trigger, move, release){
this.subscribeMapDownEvent(id,()=>{})
this.m_mapDragObject[id] = {
trigger,
move,
release
};
}
if (url == null) { releaseDragElement(){
url = key; if(this.g_currentDragElementID){
this.m_mapDragObject[this.g_currentDragElementID].release()
} }
}
this.rawAudios.set(key, url); // 全局初始化入口,当资源加载完毕后执行
initSystem() {
const audio = new Audio();
audio.src = url; this.g_canvasWidth = this.wrap.nativeElement.clientWidth;
audio.load(); this.g_canvasHeight = this.wrap.nativeElement.clientHeight;
audio.loop = loop;
audio.volume = vlomue;
audioObj[key] = audio; const sx = this.g_canvasWidth / this.g_canvasBaseW;
const sy = this.g_canvasHeight / this.g_canvasBaseH;
const s = Math.min(sx, sy);
if (callback) { this.g_mapScale = s;
audio.onended = () => { this.g_cartoon.mapScale = this.g_mapScale;
callback(); this.g_cartoon.clientWidth = this.wrap.nativeElement.clientWidth;
}; this.g_cartoon.clientHeight = this.wrap.nativeElement.clientHeight;
}
}
addUrlToImages(url) { this.m_renderArr = [];
this.rawImages.set(url, url); this.m_frontCurtainArr = [];
} this.m_renderObject = [];
this.g_enableMapDown = true;
this.g_ctx = this.canvas.nativeElement.getContext("2d");
this.canvas.nativeElement.width = this.g_canvasWidth;
this.canvas.nativeElement.height = this.g_canvasHeight;
window["curCtx"] = this.g_ctx;
// 初始化舞台
this.initStage();
this.update();
}
initStage() {
const bgWidth = 1280;
const bgHeight = 720;
this.g_cartoon.stageWidth = bgWidth*this.g_mapScale;
this.g_cartoon.stageHeight= bgHeight*this.g_mapScale;
const imageColor = this.g_cartoon.createCartoonElement("g-ackground-color", "ShapeRect").ref;
// console.log( "stageWidth: " + this.g_cartoon.stageWidth + " stageHeight" + this.g_cartoon.stageHeight)
// console.log( "clientWidth: " + this.g_cartoon.clientWidth + " clientHeight" + this.g_cartoon.clientHeight)
// console.log( "canvasWidth: " + this.g_canvasWidth + " canvasHeight" + this.g_canvasHeight)
// console.log( "mapScale: " + this.g_mapScale )
imageColor.x = this.g_cartoon.clientWidth / 2 ;
imageColor.y = this.g_cartoon.clientHeight / 2 ;
imageColor.setSize(this.g_cartoon.clientWidth, this.g_cartoon.clientHeight);
imageColor.init();
imageColor.fillColor = this.g_background_color;
this.render(imageColor, -999999)
const image = this.g_cartoon.createCartoonElement("bg_1280_720_Ruler", "MySprite").ref;
image.init(this.g_cartoon.images.get("_bg_1280_720_Ruler"));
image.x = this.g_canvasWidth / 2;
image.y = this.g_canvasHeight /2;
image.visible = this.g_EnableStageRuler
this.g_cartoon.setOrigin( image.x-(bgWidth/2*this.g_mapScale), image.y-(bgHeight/2*this.g_mapScale) )
this.g_cartoon.setRelativeOrigin( -bgWidth/2, -bgHeight/2)
image.setScaleXY(this.g_mapScale);
this.render(image, -999)
this.g_stage = image
const topElementContainer = this.g_cartoon.createCartoonElement("_bg_1280_720", "MySprite").ref;
topElementContainer.init(this.g_cartoon.images.get("_bg_1280_720"));
topElementContainer.x = this.g_canvasWidth / 2;
topElementContainer.y = this.g_canvasHeight /2;
topElementContainer.setScaleXY(this.g_mapScale);
this.render(topElementContainer, 9999)
this.g_topElementContainer = topElementContainer
const maskLayer = this.g_cartoon.createCartoonElement("_mask_layer_1280_720", "MySprite").ref;
maskLayer.init(this.g_cartoon.images.get("_mask_layer_1280_720"));
maskLayer.scaleX = this.g_canvasWidth / maskLayer.width;
maskLayer.scaleY = this.g_canvasHeight / maskLayer.height;
maskLayer.alpha = 0
maskLayer.x = this.g_canvasWidth / 2;
maskLayer.y = this.g_canvasHeight /2;
this.render(maskLayer, this.g_maskLayerZindex)
this.subscribeMapUpEvent("g-ackground-color", ()=>{
if(this.g_currentDragElementID){
this.releaseDragElement()
this.g_currentDragElementID = null;
}else{
this.g_enableMapUp = true;
}
})
}
render(ele, zIndex?:number){
this.m_renderObject.push({element:ele, zIndex:zIndex?zIndex:1})
this.m_renderObject.sort((a,b)=>{
return a.zIndex - b.zIndex
})
this.m_renderArr = []
this.m_renderObject.forEach(item=>{
this.m_renderArr.push(item.element)
})
}
sendServerEvent(key, data) {
const c = (<any> window).courseware;
c.sendEvent(key, JSON.stringify(data));
}
addServerListener(msg_key, callback) {
const c = (<any> window).courseware;
c.onEvent(msg_key, (data,next) => {
callback(JSON.parse(data))
next && next();
});
}
// ======================================================编写区域========================================================================== randomArray_shuffle(array) {
var input = array;
for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
paginationArray(pageNo, pageSize, array) {
var offset = (pageNo - 1) * pageSize;
return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
}
stopAllTimeout(){
this.m_setTimeoutIDs.forEach(id=>clearTimeout(id))
this.m_setTimeoutIDs = []
}
stopAllInterval(){
this.m_setIntervalIDs.forEach(id=>clearInterval(id))
this.m_setIntervalIDs = []
}
topOfRenderArray(element){
let index = this.m_renderArr.indexOf(element)
if(index !=-1){
this.m_renderArr.splice(index, 1)
this.m_renderArr.push(element)
}
}
/** setRenderZIndex(element, zIndex){
* 添加默认数据 便于无数据时的展示 let index = null;
*/ for(let i=0; i<this.m_renderObject.length; i++){
initDefaultData() { if( this.m_renderObject[i].element.id == element.id ){
index = i
}
}
if(index){
this.m_renderObject.splice(index, 1)
this.m_renderObject.push({element:element, zIndex:zIndex?zIndex:1})
this.m_renderObject.sort((a,b)=>{
return a.zIndex - b.zIndex
})
this.m_renderArr = []
this.m_renderObject.forEach(item=>{
this.m_renderArr.push(item.element)
})
}
}
deleteElementInRender(id){
let index = null;
for(let i=0; i<this.m_renderObject.length; i++){
if( this.m_renderObject[i].element.id == id ){
index = i
}
}
if(index){
this.m_renderObject.splice(index, 1)
this.m_renderObject.sort((a,b)=>{
return a.zIndex - b.zIndex
})
this.m_renderArr = []
this.m_renderObject.forEach(item=>{
this.m_renderArr.push(item.element)
})
}else{
console.warn("Can not found element id:" + id)
}
}
if (!this.data.pic_url) { enableMoveAsstant(callback){
this.data.pic_url = 'assets/play/default/pic.jpg'; if (this.m_moveAsstantIntervalId) {
this.data.pic_url_2 = 'assets/play/default/pic.jpg'; this.g_enableDragging = false;
clearInterval(this.m_moveAsstantIntervalId)
} }
this.m_moveAsstantIntervalId = setInterval(() => {
if(this.g_enableDragging){
callback()
}else{
let moveX = Math.abs(this.g_dragFirstClickX - this.g_clickX)
let moveY = Math.abs(this.g_dragFirstClickY - this.g_clickY)
if (moveX > this.g_enableDragDistance || moveY > this.g_enableDragDistance) {
this.g_enableDragging = true;
}
}
}, 50)
} }
disableMoveAsstant(){
this.g_enableDragging = false;
clearInterval(this.m_moveAsstantIntervalId)
}
/** cleanSystemVar(){
* 添加预加载图片 this.m_mapDownQueue = {}
*/ this.m_mapDownArray = []
initImg() { this.m_mapDownObject = []
this.m_mapMoveArray = []
this.m_mapMoveObject = []
this.m_mapUpQueue = {}
this.m_mapUpArray = []
this.m_mapUpObject = []
this.m_mapDragQueue = []
this.m_mapDragArray = []
this.m_mapDragObject = []
this.stopAllInterval();
this.stopAllTimeout()
this.g_cartoon.stopAllAudio()
this.resetLongAudio();
}
this.addUrlToImages(this.data.pic_url); getMaxSubstringLength(str){
this.addUrlToImages(this.data.pic_url_2); let maxLength = 0;
let subSubstring = str.split(" ")
for (let index=0; index<subSubstring.length; index++) {
if(subSubstring[index].length > maxLength){
maxLength = subSubstring[index].length;
}
}
return maxLength
}
setLeftCornerTest(){
const bgRect = new ShapeRect();
bgRect.setSize(57, 65);
bgRect.fillColor = '#f8c224';
const sx = this.g_canvasWidth / this.g_canvasBaseW;
bgRect.setScaleXY(sx);
bgRect.x = 65 * sx;
this.g_partTitle_x = bgRect.x
this.g_mainTitle_x = bgRect.x + 80 * sx
bgRect.alpha = 0.5
bgRect.visible = this.g_showLeftCornerTest
this.render(bgRect, 9999);
} }
/** alignCenter(elementArray, spacing, laseX = 0, withAni?, callback?){
* 添加预加载音频 let totlaWidth = 0
*/ let length = elementArray.length
initAudio() { elementArray.forEach(element => {
let bd = element.ref.getBoundingBox()
totlaWidth += bd.width
});
totlaWidth += (elementArray.length-1) * spacing
// laseX = laseX? laseX: this.g_canvasWidth / 2 - totlaWidth/2;
elementArray.forEach((element, index) => {
let bd = element.ref.getBoundingBox()
if(withAni){
tweenChange(element.ref, {x: laseX + bd.width / 2}, 0.2, ()=>{
this.g_cartoon.saveSize(element.id)
if(length == (index+1)){
callback && callback()
}
})
}else{
element.ref.x = laseX + bd.width / 2
this.g_cartoon.saveSize(element.id)
if(length == (index+1)){
callback && callback()
}
}
// 音频资源 laseX = (laseX + bd.width + spacing)
this.addUrlToAudioObj(this.data.audio_url); });
this.addUrlToAudioObj(this.data.audio_url_2); return totlaWidth
}
// 音效 alignLeft(elementArray, spacing, startX = 0, withAni?, callback?){
this.addUrlToAudioObj('click', this.rawAudios.get('click'), 0.3); let laseX = startX;
elementArray.forEach((element, index) => {
let bd = element.ref.getBoundingBox()
if(withAni){
tweenChange(element.ref, {x: laseX + bd.width / 2}, 0.2, ()=>{
this.g_cartoon.saveSize(element.id)
if(length == (index+1)){
callback && callback()
}
})
}else{
element.ref.x = laseX + bd.width / 2
this.g_cartoon.saveSize(element.id)
if(length == (index+1)){
callback && callback()
}
}
laseX = (laseX + bd.width + spacing)
});
} }
createTestLine(x, y, height, color?){
var colorAll = ['#ff0000','#eb4310','#f6941d','#fbb417','#ffff00','#cdd541','#99cc33','#3f9337','#219167','#239676','#24998d','#1f9baa','#0080ff','#3366cc','#333399','#003366','#800080','#a1488e','#c71585','#bd2158'];
color = color ? color : colorAll[Math.floor(Math.random()*20)]
this.render(this.g_cartoon.createRectangula({
width: 5,
height: height,
x: x,
y: y,
fillColor: color
}), 9999)
}
getSuitSizeBackground(key, width){
let bgAll = multiSizeBackground[key]
if(!bgAll){
return ""
}
let suitFileName = ""
for(let fileName in bgAll){
if( Number(fileName) >= width){
suitFileName = bgAll[fileName]
break
}
}
return suitFileName
}
/**
* 初始化数据
*/
initData() {
const sx = this.canvasWidth / this.canvasBaseW;
const sy = this.canvasHeight / this.canvasBaseH;
const s = Math.min(sx, sy);
this.mapScale = s;
// this.mapScale = sx;
// this.mapScale = sy;
this.renderArr = [];
}
/**
* 初始化试图
*/
initView() {
this.initPic();
this.initBottomPart();
}
initBottomPart() {
const btnLeft = new MySprite();
btnLeft.init(this.images.get('btn_left'));
btnLeft.x = this.canvasWidth - 150 * this.mapScale;
btnLeft.y = this.canvasHeight - 100 * this.mapScale;
btnLeft.setScaleXY(this.mapScale);
this.renderArr.push(btnLeft);
this.btnLeft = btnLeft;
const btnRight = new MySprite();
btnRight.init(this.images.get('btn_right'));
btnRight.x = this.canvasWidth - 50 * this.mapScale;
btnRight.y = this.canvasHeight - 100 * this.mapScale;
btnRight.setScaleXY(this.mapScale);
this.renderArr.push(btnRight);
this.btnRight = btnRight;
}
initPic() {
const maxW = this.canvasWidth * 0.7;
const pic1 = new MySprite();
pic1.init(this.images.get(this.data.pic_url));
pic1.x = this.canvasWidth / 2;
pic1.y = this.canvasHeight / 2;
pic1.setScaleXY(maxW / pic1.width);
this.renderArr.push(pic1);
this.pic1 = pic1;
const label1 = new Label();
label1.text = this.data.text;
label1.textAlign = 'center';
label1.fontSize = 50;
label1.fontName = 'BRLNSDB';
label1.fontColor = '#ffffff';
pic1.addChild(label1);
const pic2 = new MySprite(); // --------------------------------------------------
pic2.init(this.images.get(this.data.pic_url_2)); // -------------- Template function ---------------
pic2.x = this.canvasWidth / 2 + this.canvasWidth; // --------------------------------------------------
pic2.y = this.canvasHeight / 2; // --------------------------------------------------
pic2.setScaleXY(maxW / pic2.width); // --------------------------------------------------
//
// .-~~~~~~~~~-._ _.-~~~~~~~~~-.
// __.' ~. .~ `.__
// .'// \./ \\`.
// .'// | \\`.
// .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`.
// .'//.-" `-. | .-' "-.\\`.
// .'//______.============-.. \ | / ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
// --------------------------------------------------
// showParticle( element_id ) 泡泡效果
// --------------------------------------------------
// showEndPatal() / stopEndPatal() 花瓣飘落结束动画
// --------------------------------------------------
// showCorrectPatal() 指定元素上面飘花
// --------------------------------------------------
// convertPercentToRadian() 将百分比转换为弧长 第一个参数是百分比,第二个参数是方向 true为逆时针,false为顺时针。用于ShapeCircle换圆弧
// --------------------------------------------------
// movePaoWuxian() 元素抛物线跳
// --------------------------------------------------
// showJellyAnimation()------------------------------
// showBlingStar()----------------------显示星星效果--
// --------------------------------------------------
this.renderArr.push(pic2);
this.pic2 = pic2;
this.curPic = pic1; maskLayerShow(isShow, time) {
let element = this.g_cartoon.getCartoonElement("_mask_layer_1280_720")
if(isShow) {
tweenChange(element.ref, {alpha: 1}, time)
} else {
tweenChange(element.ref, {alpha: 0}, time)
}
} }
// 泡泡
btnLeftClicked() { showParticle(card) {
let myCard = this.g_cartoon.getCartoonElementRelativePosition(card.id)
this.lastPage(); showPopParticle(this.g_cartoon.images.get("_bubble"), { x: myCard.x , y: myCard.y }, this.g_stage);
} }
btnRightClicked() { // 选择正确动画
showCorrectPatal(card_id, showTime, callback?) {
this.nextPage(); this.m_elementPetalArr = [];
this.m_showElementPetalFlag = true;
this.addCorrectPetal(card_id);
setTimeout(()=>{
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = false;
callback && callback()
},showTime)
}
stopAllCorrectPatal(){
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = false;
} }
lastPage() { addCorrectPetal(card_id) {
if (!this.m_showElementPetalFlag) {
if (this.curPic == this.pic1) {
return; return;
} }
this.canTouch = false; let element = this.g_cartoon.getCartoonElement(card_id)
const petal = new MySprite(this.g_ctx);
const moveLen = this.canvasWidth; const id = Math.ceil(Math.random() * 3);
tweenChange(this.pic1, {x: this.pic1.x + moveLen}, 1); petal.init(this.g_cartoon.images.get(this.m_PetalImage + id));
tweenChange(this.pic2, {x: this.pic2.x + moveLen}, 1, () => {
this.canTouch = true;
this.curPic = this.pic1;
});
}
nextPage() { const randomS = (Math.random() * 0.4 + 0.6) * this.g_mapScale * 0.5;
petal.setScaleXY(randomS);
if (this.curPic == this.pic2) { const randomR = Math.random() * 360;
return; petal.rotation = randomR;
}
this.canTouch = false; const randomX = Math.random() * element.ref.width * this.g_mapScale;
const moveLen = this.canvasWidth; petal.x = element.ref.x - (element.ref.width * this.g_mapScale / 2) + randomX;
tweenChange(this.pic1, {x: this.pic1.x - moveLen}, 1); petal.y = element.ref.y - (element.ref.height * this.g_mapScale / 2);
tweenChange(this.pic2, {x: this.pic2.x - moveLen}, 1, () => {
this.canTouch = true;
this.curPic = this.pic2;
});
}
pic1Clicked() { const randomT = 1 + Math.random() * 2;
this.playAudio(this.data.audio_url); petal["time"] = randomT;
}
pic2Clicked() { let randomTR = 360 * Math.random(); // - 180;
this.playAudio(this.data.audio_url_2); if (Math.random() < 0.5) {
randomTR *= -1;
}
petal["tr"] = randomTR;
this.m_elementPetalArr.push(petal);
moveItem(
petal,
petal.x,
element.ref.y + (element.ref.height * this.g_mapScale / 2),
petal["time"],
() => {
removeItemFromArr(this.m_elementPetalArr, petal);
}
);
rotateItem(petal, petal["tr"], petal["time"]);
setTimeout(() => {
this.addCorrectPetal(card_id);
}, 200);
} }
// 结束动画花瓣飘落
showEndPatal() {
this.m_endPageArr = [];
this.m_showPetalFlag = true;
this.addPetal();
}
stopEndPatal() {
this.m_endPageArr = [];
this.m_showPetalFlag = false;
}
addPetal() {
mapDown(event) { if (!this.m_showPetalFlag) {
if (!this.canTouch) {
return;
}
if ( this.checkClickTarget(this.btnLeft) ) {
this.btnLeftClicked();
return; return;
} }
const petal = this.getPetal();
this.m_endPageArr.push(petal);
moveItem(
petal,
petal.x,
this.g_canvasHeight + petal.height * petal.scaleY,
petal["time"],
() => {
removeItemFromArr(this.m_endPageArr, petal);
}
);
rotateItem(petal, petal["tr"], petal["time"]);
setTimeout(() => {
this.addPetal();
}, 100);
}
if ( this.checkClickTarget(this.btnRight) ) { getPetal() {
this.btnRightClicked(); const petal = new MySprite(this.g_ctx);
return;
}
if ( this.checkClickTarget(this.pic1) ) { const id = Math.ceil(Math.random() * 3);
this.pic1Clicked(); petal.init(this.g_cartoon.images.get(this.m_PetalImage + id));
return;
}
if ( this.checkClickTarget(this.pic2) ) { const randomS = (Math.random() * 0.4 + 0.6) * this.g_mapScale;
this.pic2Clicked(); petal.setScaleXY(randomS);
return;
}
} const randomR = Math.random() * 360;
petal.rotation = randomR;
mapMove(event) { const randomX = Math.random() * this.g_canvasWidth;
petal.x = randomX;
petal.y = (-petal.height / 2) * petal.scaleY;
} const randomT = 2 + Math.random() * 5;
petal["time"] = randomT;
mapUp(event) { let randomTR = 360 * Math.random(); // - 180;
if (Math.random() < 0.5) {
randomTR *= -1;
}
petal["tr"] = randomTR;
return petal;
} }
showJellyAnimation(element_id, callback?){
let element = this.g_cartoon.getCartoonElement(element_id).ref
tweenChange(element,{ scaleX: this.g_mapScale * element.initScaleX * 1.1 , scaleY: this.g_mapScale * element.initScaleY * 1.1 }, 0.1, ()=>{
tweenChange(element,{ scaleX: this.g_mapScale * element.initScaleX * 0.9 , scaleY: this.g_mapScale * element.initScaleY * 0.9 }, 0.1, ()=>{
tweenChange(element,{ scaleX: element.initScaleX , scaleY: element.initScaleY }, 0.1, ()=>{
callback && callback()
})
})
})
}
update() { showShakeAnimation(element_id, callback?){
let element = this.g_cartoon.getCartoonElement(element_id).ref
// ---------------------------------------------------------- let originX = element.x
this.animationId = window.requestAnimationFrame(this.update.bind(this)); tweenChange(element,{ x: originX - 10*this.g_mapScale }, 0.1, ()=>{
// 清除画布内容 tweenChange(element,{ x: originX + 10*this.g_mapScale }, 0.1, ()=>{
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); tweenChange(element,{ x: originX }, 0.1, ()=>{
// tween 更新动画 callback && callback()
TWEEN.update(); })
// ---------------------------------------------------------- })
})
}
convertPercentToRadian(per, direction){
let radian = 0;
if(direction) { //逆时针
if(per*360 > 270){
radian = 361 - (per*360 - 270)
}else{
radian = 270 - per*360
}
}else{ //顺时针
if(per*360 > 90){
radian = per*360 - 90
}else{
radian = 270 + per*360
}
}
return (radian * Math.PI) / 180;
}
this.updateArr(this.renderArr); showBlingStar(element, callback?){
let rect = element.getBoundingBox()
showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 0.5);
this.m_setTimeoutIDs.push(setTimeout(() => {
callback && callback()
}, 2000))
// setTimeout(()=>{
// showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 1.8);
// },200)
// setTimeout(()=>{
// showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 1.6);
// },400)
}
movePaoWuxian(element,dis,time,callback?){
let disX = dis.x - element.x
let disY = (element.y - dis.y)
let count = 0
let runTime = time/5
let vx = disX/runTime
let a = -0.05
let vy0 = disY/runTime - 0.5*a*runTime
let id = setInterval(()=>{
element.x += vx
element.y -= vy0 + a*count
count++;
if(count>runTime){
clearInterval(id)
callback && callback()
}
}, 5);
}
showBalloons(maxBalloon = 10) {
let balloonImgList = [
"_balloon_blue",
"_balloon_green",
"_balloon_orange",
"_balloon_pink",
"_balloon_red",
"_balloon_yellow",
];
for (var i = 0; i < maxBalloon; ++i) {
let balloon = new MySprite();
balloon.init(
this.g_cartoon.images.get(balloonImgList[this.randomInt(balloonImgList.length)])
);
let leftBorder = -640;
let rightBorder = 640;
balloon.x = this.randomInt(leftBorder, rightBorder);
balloon.y = 720 / 2 + this.randomInt(400);
this.g_topElementContainer.addChild(balloon);
balloon.scaleX = 0;
balloon.scaleY = 0;
tweenChange(
balloon, {
scaleX: 1 + Math.random() * 0.3 - 0.15,
scaleY: 1 + Math.random() * 0.3 - 0.15,
},
0.5
);
let wholeTime = 3;
if (i < 4) {
wholeTime = 3 + i;
}
tweenChange(
balloon,
{ y: -720 / 2 - this.randomInt(200) },
wholeTime,
()=>{
this.g_topElementContainer.removeChild(balloon)
},
TWEEN.Easing.Quadratic.In
);
let time = Math.random() * wholeTime;
tweenChange(
balloon,
{
x: this.Between(
leftBorder,
rightBorder,
balloon.x + Math.min(time * 50, this.randomInt(200))
),
},
time,
() => {
tweenChange(
balloon,
{
x: this.Between(
leftBorder,
rightBorder,
balloon.x - Math.min(time * 50, this.randomInt(200))
),
},
wholeTime - time
);
}
);
}
} }
randomInt(a, b = 0) {
let max = Math.max(a, b);
let min = Math.min(a, b);
return Math.floor(Math.random() * (max - min) + min);
}
Between(a, b, c) {
return [a, b, c].sort((a, b) => a - b)[1];
}
} }
\ No newline at end of file
const res = [ const localImages = {
'_bg_1280_720_Ruler': 'assets/default/images/1280_720_Ruler.png',
'_mask_layer_1280_720': 'assets/default/images/mask_layer_1280_720.png',
'_bg_240_180': 'assets/default/images/bg_240_180.png',
'_bg_453_251': 'assets/default/images/bg_453_251.png',
'_bg_1280_222': 'assets/default/images/bg_1280_222.png',
'_bg_1280_720': 'assets/default/images/bg_1280_720.png',
'_bg_200_200': 'assets/default/images/bg_200_200.png',
'_bg_30_30': 'assets/default/images/bg_30_30.png',
'_bg_500_600': 'assets/default/images/bg_500_600.png',
'_bg_50_50': 'assets/default/images/bg_50_50.png',
'_bg_75_50': 'assets/default/images/bg_75_50.png',
'_bg_50_20': 'assets/default/images/bg_50_20.png',
'_bg_75_50_black': 'assets/default/images/bg_75_50_black.png',
'_flag': 'assets/default/images/flag.png',
'_go': 'assets/default/images/go.png',
'_header': 'assets/default/images/header.png',
'_ready': 'assets/default/images/ready.png',
'_replay': 'assets/default/images/replay.png',
'_scrap-pic-1': 'assets/default/images/scrap-pic-1.png',
'_scrap-pic-2': 'assets/default/images/scrap-pic-2.png',
'_scrap-pic-3': 'assets/default/images/scrap-pic-3.png',
'_sm-pic-1': 'assets/default/images/sm-pic-1.png',
'_sm-pic-2': 'assets/default/images/sm-pic-2.png',
'_sm-pic-3': 'assets/default/images/sm-pic-3.png',
'_sm-pic-4': 'assets/default/images/sm-pic-4.png',
'_star': 'assets/default/images/star.png',
'_bubble': 'assets/default/images/bubble.png',
'_image_none': 'assets/default/images/image_none.png',
'_balloon_blue': 'assets/default/images/balloon_blue.png',
'_balloon_green': 'assets/default/images/balloon_green.png',
'_balloon_orange': 'assets/default/images/balloon_orange.png',
'_balloon_pink': 'assets/default/images/balloon_pink.png',
'_balloon_red': 'assets/default/images/balloon_red.png',
'_balloon_yellow': 'assets/default/images/balloon_yellow.png',
'bg_question': 'assets/play/bg_question.png',
'btn_next': 'assets/play/btn_next.png',
'btn_pre': 'assets/play/btn_pre.png',
'bg_main_mask': 'assets/play/bg_main_mask.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"],
]; const localAudios = {
'sm-back': "assets/default/audio/sm-back.mp3",
'sm-display': "assets/default/audio/sm-display.mp3",
'sm-wrong': "assets/default/audio/sm-wrong.mp3",
'sm-win': "assets/default/audio/sm-win.mp3",
'sm-in': "assets/default/audio/sm-in.mp3",
'sm-out': "assets/default/audio/sm-out.mp3",
'sm-click': "assets/default/audio/sm-click.mp3",
'sm-start': "assets/default/audio/sm-start.mp3",
'sm-correct': 'assets/default/audio/sm-correct.mp3',
'sm-star': "assets/default/audio/sm-star.mp3",
'sm-choice-complete': 'assets/default/audio/sm-choice-complete.mp3',
'sm-choice-correct': 'assets/default/audio/sm-choice-correct.mp3',
'sm-choice-error': 'assets/default/audio/sm-choice-error.mp3',
'sm-choice-in': 'assets/default/audio/sm-choice-in.mp3',
'sm-choice-show-answer': 'assets/default/audio/sm-choice-show-answer.mp3',
'sm-choice-timeup-0': 'assets/default/audio/sm-choice-timeup-0.mp3',
'sm-choice-timeup-3': 'assets/default/audio/sm-choice-timeup-3.mp3',
'sm-go': 'assets/default/audio/sm-go.mp3',
'sm-ready': 'assets/default/audio/sm-ready.mp3',
'button': 'assets/play/sound/button.mp3',
'popup': 'assets/play/sound/popup.mp3',
'correct': 'assets/play/sound/correct.mp3',
};
const multiSizeBackground = {
const resAudio = [ }
['click', "assets/play/music/click.mp3"], export { localImages, localAudios, multiSizeBackground };
\ No newline at end of file
];
export {res, resAudio};
export const defaultData = {
version: "1.0",
dataKey: "DataKey_JM04_3",
title: {
NO: "C",
mainText: "Listen, circle and write.",
mainTextAudio_url: "",
},
size: {
wh: "12*12"
},
dataArray: [{ image_url: "", audio_url: "", text: "", uuid: "9803c50c-3638-4a6a-a4f8-719bdeaacede", direction: "left" }],
grid: [
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}],
[{index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}, {index: -1, text: ""}]
]
}
export const demoData = {
"version": "1.0",
"dataKey": "DataKey_JM04_3",
"title": {
"NO": "C",
"mainText": "Listen, circle and write.",
"mainTextAudio_url": ""
},
"dataArray": [{
"image_url": "demo_1",
"audio_url": "",
"text": "SP-1",
"uuid": "9803c50c-3638-4a6a-a4f8-719bdeaacede",
"direction": "right"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-2",
"uuid": "2e780bc2-9f79-42f5-9358-6a8da7a9e20c",
"direction": "right"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-3",
"uuid": "c038eee3-0a93-42b8-8099-e55ef6d41430",
"direction": "right"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-4",
"uuid": "041408b2-b1b7-43d4-b6b1-a6e3d9151c08",
"direction": "down"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-5",
"uuid": "d07794d6-afec-46e9-8458-4705905d5529",
"direction": "down"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-6",
"uuid": "748c35b2-ffcf-4811-ae3e-987c44051113",
"direction": "down"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-7",
"uuid": "c4160e6b-0090-47f0-946e-a0e17c00be8a",
"direction": "down"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-8",
"uuid": "20ba251c-e1c5-40e5-9892-0edd1de30637",
"direction": "right"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-9",
"uuid": "8cb1193c-764e-422a-b202-9d5a9488f967",
"direction": "down"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-10",
"uuid": "62e230f5-ae27-41ba-af5d-76f47dc12604",
"direction": "right"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-11",
"uuid": "ff03aec8-9934-412f-a026-96abd81c83f1",
"direction": "down"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-12",
"uuid": "de7461bb-5188-4210-afac-0703a633e9c1",
"direction": "right"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-13",
"uuid": "1d2d18b9-9b82-490d-bc82-a93925389aa6",
"direction": "right"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-14",
"uuid": "8d26cc84-fca9-40e1-af76-400f76604d5a",
"direction": "right"
}, {
"image_url": "demo_1",
"audio_url": "",
"text": "SP-15",
"uuid": "cfcd7693-1d40-447e-9541-977f867476ae",
"direction": "right"
}],
"grid": [
[{
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["8cb1193c-764e-422a-b202-9d5a9488f967"],
"text": "9"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["041408b2-b1b7-43d4-b6b1-a6e3d9151c08"],
"text": "4"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["d07794d6-afec-46e9-8458-4705905d5529"],
"text": "5"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["748c35b2-ffcf-4811-ae3e-987c44051113"],
"text": "6"
}],
[{
"index": ["9803c50c-3638-4a6a-a4f8-719bdeaacede"],
"text": "1"
}, {
"index": ["9803c50c-3638-4a6a-a4f8-719bdeaacede"],
"text": "A"
}, {
"index": ["9803c50c-3638-4a6a-a4f8-719bdeaacede"],
"text": "B"
}, {
"index": ["8cb1193c-764e-422a-b202-9d5a9488f967", "9803c50c-3638-4a6a-a4f8-719bdeaacede"],
"text": "A"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["cfcd7693-1d40-447e-9541-977f867476ae"],
"text": "5"
}, {
"index": ["041408b2-b1b7-43d4-b6b1-a6e3d9151c08", "cfcd7693-1d40-447e-9541-977f867476ae"],
"text": "A"
}, {
"index": ["cfcd7693-1d40-447e-9541-977f867476ae"],
"text": "B"
}, {
"index": ["cfcd7693-1d40-447e-9541-977f867476ae"],
"text": "C"
}, {
"index": ["cfcd7693-1d40-447e-9541-977f867476ae"],
"text": "D"
}, {
"index": ["d07794d6-afec-46e9-8458-4705905d5529", "cfcd7693-1d40-447e-9541-977f867476ae"],
"text": "A"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["748c35b2-ffcf-4811-ae3e-987c44051113"],
"text": "A"
}],
[{
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["20ba251c-e1c5-40e5-9892-0edd1de30637"],
"text": "8"
}, {
"index": ["20ba251c-e1c5-40e5-9892-0edd1de30637", "8cb1193c-764e-422a-b202-9d5a9488f967"],
"text": "A"
}, {
"index": ["20ba251c-e1c5-40e5-9892-0edd1de30637"],
"text": "B"
}, {
"index": ["20ba251c-e1c5-40e5-9892-0edd1de30637"],
"text": "C"
}, {
"index": ["20ba251c-e1c5-40e5-9892-0edd1de30637"],
"text": "D"
}, {
"index": ["041408b2-b1b7-43d4-b6b1-a6e3d9151c08", "20ba251c-e1c5-40e5-9892-0edd1de30637"],
"text": "B"
}, {
"index": [],
"text": ""
}, {
"index": ["ff03aec8-9934-412f-a026-96abd81c83f1"],
"text": "1"
}, {
"index": ["1d2d18b9-9b82-490d-bc82-a93925389aa6"],
"text": "3"
}, {
"index": ["d07794d6-afec-46e9-8458-4705905d5529", "1d2d18b9-9b82-490d-bc82-a93925389aa6"],
"text": "B"
}, {
"index": ["1d2d18b9-9b82-490d-bc82-a93925389aa6"],
"text": "A"
}, {
"index": ["1d2d18b9-9b82-490d-bc82-a93925389aa6"],
"text": "A"
}, {
"index": ["748c35b2-ffcf-4811-ae3e-987c44051113", "1d2d18b9-9b82-490d-bc82-a93925389aa6"],
"text": "B"
}],
[{
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["8cb1193c-764e-422a-b202-9d5a9488f967"],
"text": "B"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["041408b2-b1b7-43d4-b6b1-a6e3d9151c08"],
"text": "C"
}, {
"index": [],
"text": ""
}, {
"index": ["ff03aec8-9934-412f-a026-96abd81c83f1"],
"text": "A"
}, {
"index": [],
"text": ""
}, {
"index": ["d07794d6-afec-46e9-8458-4705905d5529"],
"text": "C"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["748c35b2-ffcf-4811-ae3e-987c44051113"],
"text": "C"
}],
[{
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["8cb1193c-764e-422a-b202-9d5a9488f967"],
"text": "C"
}, {
"index": ["c4160e6b-0090-47f0-946e-a0e17c00be8a"],
"text": "7"
}, {
"index": ["62e230f5-ae27-41ba-af5d-76f47dc12604"],
"text": "0"
}, {
"index": ["62e230f5-ae27-41ba-af5d-76f47dc12604"],
"text": "Z"
}, {
"index": ["041408b2-b1b7-43d4-b6b1-a6e3d9151c08", "62e230f5-ae27-41ba-af5d-76f47dc12604"],
"text": "D"
}, {
"index": ["62e230f5-ae27-41ba-af5d-76f47dc12604"],
"text": "Z"
}, {
"index": ["62e230f5-ae27-41ba-af5d-76f47dc12604", "ff03aec8-9934-412f-a026-96abd81c83f1"],
"text": "Z"
}, {
"index": [],
"text": ""
}, {
"index": ["d07794d6-afec-46e9-8458-4705905d5529"],
"text": "D"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["748c35b2-ffcf-4811-ae3e-987c44051113"],
"text": "D"
}],
[{
"index": ["2e780bc2-9f79-42f5-9358-6a8da7a9e20c"],
"text": "2"
}, {
"index": ["2e780bc2-9f79-42f5-9358-6a8da7a9e20c"],
"text": "A"
}, {
"index": ["2e780bc2-9f79-42f5-9358-6a8da7a9e20c"],
"text": "B"
}, {
"index": ["8cb1193c-764e-422a-b202-9d5a9488f967", "2e780bc2-9f79-42f5-9358-6a8da7a9e20c"],
"text": "C"
}, {
"index": ["c4160e6b-0090-47f0-946e-a0e17c00be8a", "2e780bc2-9f79-42f5-9358-6a8da7a9e20c"],
"text": "D"
}, {
"index": ["2e780bc2-9f79-42f5-9358-6a8da7a9e20c"],
"text": "E"
}, {
"index": ["2e780bc2-9f79-42f5-9358-6a8da7a9e20c"],
"text": "F"
}, {
"index": ["041408b2-b1b7-43d4-b6b1-a6e3d9151c08", "2e780bc2-9f79-42f5-9358-6a8da7a9e20c"],
"text": "G"
}, {
"index": ["2e780bc2-9f79-42f5-9358-6a8da7a9e20c"],
"text": "H"
}, {
"index": ["ff03aec8-9934-412f-a026-96abd81c83f1", "2e780bc2-9f79-42f5-9358-6a8da7a9e20c"],
"text": "I"
}, {
"index": ["de7461bb-5188-4210-afac-0703a633e9c1"],
"text": "2"
}, {
"index": ["d07794d6-afec-46e9-8458-4705905d5529", "de7461bb-5188-4210-afac-0703a633e9c1"],
"text": "E"
}, {
"index": ["de7461bb-5188-4210-afac-0703a633e9c1"],
"text": "A"
}, {
"index": ["de7461bb-5188-4210-afac-0703a633e9c1"],
"text": "A"
}, {
"index": ["748c35b2-ffcf-4811-ae3e-987c44051113", "de7461bb-5188-4210-afac-0703a633e9c1"],
"text": "E"
}],
[{
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["c4160e6b-0090-47f0-946e-a0e17c00be8a"],
"text": "E"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["ff03aec8-9934-412f-a026-96abd81c83f1"],
"text": "A"
}, {
"index": [],
"text": ""
}, {
"index": ["d07794d6-afec-46e9-8458-4705905d5529"],
"text": "F"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}],
[{
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["c4160e6b-0090-47f0-946e-a0e17c00be8a"],
"text": "D"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["ff03aec8-9934-412f-a026-96abd81c83f1"],
"text": "B"
}, {
"index": [],
"text": ""
}, {
"index": ["d07794d6-afec-46e9-8458-4705905d5529"],
"text": "G"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}],
[{
"index": ["c038eee3-0a93-42b8-8099-e55ef6d41430"],
"text": "3"
}, {
"index": ["c038eee3-0a93-42b8-8099-e55ef6d41430"],
"text": "A"
}, {
"index": ["c038eee3-0a93-42b8-8099-e55ef6d41430"],
"text": "B"
}, {
"index": ["c038eee3-0a93-42b8-8099-e55ef6d41430"],
"text": "C"
}, {
"index": ["c038eee3-0a93-42b8-8099-e55ef6d41430", "c4160e6b-0090-47f0-946e-a0e17c00be8a"],
"text": "D"
}, {
"index": ["c038eee3-0a93-42b8-8099-e55ef6d41430"],
"text": "E"
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": [],
"text": ""
}, {
"index": ["ff03aec8-9934-412f-a026-96abd81c83f1"],
"text": "C"
}, {
"index": ["8d26cc84-fca9-40e1-af76-400f76604d5a"],
"text": "4"
}, {
"index": ["d07794d6-afec-46e9-8458-4705905d5529", "8d26cc84-fca9-40e1-af76-400f76604d5a"],
"text": "I"
}, {
"index": ["8d26cc84-fca9-40e1-af76-400f76604d5a"],
"text": "A"
}, {
"index": ["8d26cc84-fca9-40e1-af76-400f76604d5a"],
"text": "B"
}, {
"index": ["8d26cc84-fca9-40e1-af76-400f76604d5a"],
"text": "C"
}]
]
};
import os
import json
def file_name(file_dir):
fileList =[]
for root, dirs, files in os.walk(file_dir):
fileList = files
return fileList
fileList = file_name(os.path.abspath('.'))
f = open('filename.txt', 'w')
for fn in fileList:
if fn.split(".")[0] != "creatJsonProfile":
f.write("'" + fn.split(".")[0] + "': 'assets/play/" + fn + "',\n")
f.close()
\ No newline at end of file
!function(){"use strict";function r(r){r||(r=Math.random),this.p=e(r),this.perm=new Uint8Array(512),this.permMod12=new Uint8Array(512);for(var t=0;t<512;t++)this.perm[t]=this.p[255&t],this.permMod12[t]=this.perm[t]%12}function e(r){var e,t=new Uint8Array(256);for(e=0;e<256;e++)t[e]=e;for(e=0;e<255;e++){var a=e+1+~~(r()*(255-e)),i=t[e];t[e]=t[a],t[a]=i}return t}var t=.5*(Math.sqrt(3)-1),a=(3-Math.sqrt(3))/6,i=1/3,o=1/6,n=(Math.sqrt(5)-1)/4,f=(5-Math.sqrt(5))/20;r.prototype={grad3:new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),grad4:new Float32Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]),noise2D:function(r,e){var i,o,n=this.permMod12,f=this.perm,s=this.grad3,v=0,h=0,d=0,l=(r+e)*t,p=Math.floor(r+l),u=Math.floor(e+l),M=(p+u)*a,m=p-M,y=u-M,w=r-m,c=e-y;w>c?(i=1,o=0):(i=0,o=1);var g=w-i+a,x=c-o+a,A=w-1+2*a,q=c-1+2*a,D=255&p,U=255&u,b=.5-w*w-c*c;if(b>=0){var F=3*n[D+f[U]];b*=b,v=b*b*(s[F]*w+s[F+1]*c)}var N=.5-g*g-x*x;if(N>=0){var S=3*n[D+i+f[U+o]];N*=N,h=N*N*(s[S]*g+s[S+1]*x)}var P=.5-A*A-q*q;if(P>=0){var T=3*n[D+1+f[U+1]];P*=P,d=P*P*(s[T]*A+s[T+1]*q)}return 70*(v+h+d)},noise3D:function(r,e,t){var a,n,f,s,v,h,d,l,p,u,M=this.permMod12,m=this.perm,y=this.grad3,w=(r+e+t)*i,c=Math.floor(r+w),g=Math.floor(e+w),x=Math.floor(t+w),A=(c+g+x)*o,q=c-A,D=g-A,U=x-A,b=r-q,F=e-D,N=t-U;b>=F?F>=N?(v=1,h=0,d=0,l=1,p=1,u=0):b>=N?(v=1,h=0,d=0,l=1,p=0,u=1):(v=0,h=0,d=1,l=1,p=0,u=1):F<N?(v=0,h=0,d=1,l=0,p=1,u=1):b<N?(v=0,h=1,d=0,l=0,p=1,u=1):(v=0,h=1,d=0,l=1,p=1,u=0);var S=b-v+o,P=F-h+o,T=N-d+o,_=b-l+2*o,j=F-p+2*o,k=N-u+2*o,z=b-1+3*o,B=F-1+3*o,C=N-1+3*o,E=255&c,G=255&g,H=255&x,I=.6-b*b-F*F-N*N;if(I<0)a=0;else{var J=3*M[E+m[G+m[H]]];I*=I,a=I*I*(y[J]*b+y[J+1]*F+y[J+2]*N)}var K=.6-S*S-P*P-T*T;if(K<0)n=0;else{var L=3*M[E+v+m[G+h+m[H+d]]];K*=K,n=K*K*(y[L]*S+y[L+1]*P+y[L+2]*T)}var O=.6-_*_-j*j-k*k;if(O<0)f=0;else{var Q=3*M[E+l+m[G+p+m[H+u]]];O*=O,f=O*O*(y[Q]*_+y[Q+1]*j+y[Q+2]*k)}var R=.6-z*z-B*B-C*C;if(R<0)s=0;else{var V=3*M[E+1+m[G+1+m[H+1]]];R*=R,s=R*R*(y[V]*z+y[V+1]*B+y[V+2]*C)}return 32*(a+n+f+s)},noise4D:function(r,e,t,a){var i,o,s,v,h,d=(this.permMod12,this.perm),l=this.grad4,p=(r+e+t+a)*n,u=Math.floor(r+p),M=Math.floor(e+p),m=Math.floor(t+p),y=Math.floor(a+p),w=(u+M+m+y)*f,c=u-w,g=M-w,x=m-w,A=y-w,q=r-c,D=e-g,U=t-x,b=a-A,F=0,N=0,S=0,P=0;q>D?F++:N++,q>U?F++:S++,q>b?F++:P++,D>U?N++:S++,D>b?N++:P++,U>b?S++:P++;var T,_,j,k,z,B,C,E,G,H,I,J;T=F>=3?1:0,_=N>=3?1:0,j=S>=3?1:0,k=P>=3?1:0,z=F>=2?1:0,B=N>=2?1:0,C=S>=2?1:0,E=P>=2?1:0,G=F>=1?1:0,H=N>=1?1:0,I=S>=1?1:0,J=P>=1?1:0;var K=q-T+f,L=D-_+f,O=U-j+f,Q=b-k+f,R=q-z+2*f,V=D-B+2*f,W=U-C+2*f,X=b-E+2*f,Y=q-G+3*f,Z=D-H+3*f,$=U-I+3*f,rr=b-J+3*f,er=q-1+4*f,tr=D-1+4*f,ar=U-1+4*f,ir=b-1+4*f,or=255&u,nr=255&M,fr=255&m,sr=255&y,vr=.6-q*q-D*D-U*U-b*b;if(vr<0)i=0;else{var hr=d[or+d[nr+d[fr+d[sr]]]]%32*4;vr*=vr,i=vr*vr*(l[hr]*q+l[hr+1]*D+l[hr+2]*U+l[hr+3]*b)}var dr=.6-K*K-L*L-O*O-Q*Q;if(dr<0)o=0;else{var lr=d[or+T+d[nr+_+d[fr+j+d[sr+k]]]]%32*4;dr*=dr,o=dr*dr*(l[lr]*K+l[lr+1]*L+l[lr+2]*O+l[lr+3]*Q)}var pr=.6-R*R-V*V-W*W-X*X;if(pr<0)s=0;else{var ur=d[or+z+d[nr+B+d[fr+C+d[sr+E]]]]%32*4;pr*=pr,s=pr*pr*(l[ur]*R+l[ur+1]*V+l[ur+2]*W+l[ur+3]*X)}var Mr=.6-Y*Y-Z*Z-$*$-rr*rr;if(Mr<0)v=0;else{var mr=d[or+G+d[nr+H+d[fr+I+d[sr+J]]]]%32*4;Mr*=Mr,v=Mr*Mr*(l[mr]*Y+l[mr+1]*Z+l[mr+2]*$+l[mr+3]*rr)}var yr=.6-er*er-tr*tr-ar*ar-ir*ir;if(yr<0)h=0;else{var wr=d[or+1+d[nr+1+d[fr+1+d[sr+1]]]]%32*4;yr*=yr,h=yr*yr*(l[wr]*er+l[wr+1]*tr+l[wr+2]*ar+l[wr+3]*ir)}return 27*(i+o+s+v+h)}},r._buildPermutationTable=e,"undefined"!=typeof define&&define.amd&&define(function(){return r}),"undefined"!=typeof exports?exports.SimplexNoise=r:"undefined"!=typeof window&&(window.SimplexNoise=r),"undefined"!=typeof module&&(module.exports=r)}();
//# sourceMappingURL=simplex-noise.min.js.map
\ No newline at end of file
import os
import json
def file_name(file_dir):
fileList =["bg_kuang", "bg_kuang2", "bg_light"]
f = open('filename.txt', 'w');
blank = False
for root, dirs, files in os.walk(file_dir):
for fileName in files:
if root.split("\\")[-1]=="frame" or root.split("\\")[-1]=="sound" or root.split("\\")[-1]=="play" or (root.split("\\")[-1] in fileList):
blank = True
if root.split("\\")[-1] != "play":
f.write("'" + fileName.split(".")[0] + "': 'assets/play/" + root.split("\\")[-1] + "/" + fileName + "',\n")
else:
f.write("'" + fileName.split(".")[0] + "': 'assets/" + root.split("\\")[-1] + "/" + fileName + "',\n")
if blank:
f.write("\n")
blank = False
f.close()
fileList = file_name(os.path.abspath('.'))
'bg_card_4_1': 'assets/play/bg_card_4_1.png',
'bg_card_4_2': 'assets/play/bg_card_4_2.png',
'bg_card_4_3': 'assets/play/bg_card_4_3.png',
'bg_card_4_4': 'assets/play/bg_card_4_4.png',
'bg_card_6_1': 'assets/play/bg_card_6_1.png',
'bg_card_6_2': 'assets/play/bg_card_6_2.png',
'bg_card_6_3': 'assets/play/bg_card_6_3.png',
'bg_card_6_4': 'assets/play/bg_card_6_4.png',
'bg_card_6_5': 'assets/play/bg_card_6_5.png',
'bg_card_6_6': 'assets/play/bg_card_6_6.png',
'bg_text_target': 'assets/play/bg_text_target.png',
'bg_title_part': 'assets/play/bg_title_part.png',
'circle_h': 'assets/play/circle_h.png',
'circle_l': 'assets/play/circle_l.png',
'circle_r': 'assets/play/circle_r.png',
'creatJsonProfile': 'assets/play/creatJsonProfile.py',
'filename': 'assets/play/filename.txt',
'icon_audio_container': 'assets/play/icon_audio_container.png',
'icon_paly': 'assets/play/icon_paly.png',
'icon_pause': 'assets/play/icon_pause.png',
'num_icon_1': 'assets/play/num_icon_1.png',
'num_icon_2': 'assets/play/num_icon_2.png',
'num_icon_3': 'assets/play/num_icon_3.png',
'num_icon_4': 'assets/play/num_icon_4.png',
'num_icon_5': 'assets/play/num_icon_5.png',
'num_icon_6': 'assets/play/num_icon_6.png',
'part_number_bg': 'assets/play/part_number_bg.png',
'radio_inner': 'assets/play/radio_inner.png',
'radio_out': 'assets/play/radio_out.png',
'resizeImg': 'assets/play/resizeImg.py',
'button': 'assets/play/sound/button.mp3',
'correct': 'assets/play/sound/correct.mp3',
'popup': 'assets/play/sound/popup.mp3',
import os
import shutil
from PIL import Image
fileName = os.listdir('./')
withBorder = False
border_left = ""
border_right = ""
imageName = input("图片名:")
if input("是否包含边框? (y/n):")=="y":
withBorder = True
if withBorder:
border_left = input("左边框文件名:")
border_right = input("右边框文件名:")
number = int(input("数量:"))
if os.path.exists('./' + imageName + '/'):
shutil.rmtree('./' + imageName + '/')
os.mkdir('./' + imageName + '/')
pic = Image.open('./' + imageName + '.PNG')
width = pic.width
height = pic.height
f = open('./' + imageName + '/' + imageName + '_map.txt', 'w')
if withBorder:
borderImg_left, borderImg_right = Image.open('./' + border_left + '.PNG'), Image.open('./' + border_right + '.PNG')
for index in range(1, number):
newpic = pic.resize((width*index, height),Image.ANTIALIAS)
loc1, loc2, loc3 = (0, 0), (borderImg_left.width, 0), (borderImg_left.width +newpic.width, 0)
join_pic = Image.new('RGBA', (borderImg_left.width + newpic.width + borderImg_right.width, newpic.height))
join_pic.paste(borderImg_left, loc1)
join_pic.paste(newpic, loc2)
join_pic.paste(borderImg_right, loc3)
join_pic.save('./' + imageName + '/' + imageName + '_' + str(index) + 'x.PNG')
f.write('"' + str(width*index) + '": "' + imageName + '_' + str(index) + 'x",\n')
f.close()
else:
for index in range(1, number):
newpic = pic.resize((width*index, height),Image.ANTIALIAS)
newpic.save('./' + imageName + '/' + imageName + '_' + str(index) + 'x.PNG')
f.write('"' + str(width*index) + '": "' + imageName + '_' + str(index) + 'x",\n')
f.close()
\ No newline at end of file
/* You can add global styles to this file, and also import other style files */ /* You can add global styles to this file, and also import other style files */
@import "~ng-zorro-antd/ng-zorro-antd.min.css";
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment