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>
<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 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>
<input type="text" nz-input [(ngModel)]="item.text" (blur)="save()">
<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>
<app-upload-image-with-preview
[picUrl]="item.pic_url"
(imageUploaded)="onImageUploadSuccess($event, 'pic_url')"
></app-upload-image-with-preview>
<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>
<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>
</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({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
// 储存数据用
saveKey = "test_0011";
// 储存对象
item;
export class FormComponent implements OnInit, OnChanges, OnDestroy {
_item: any;
KEY = 'DataKey_JM04_3';
constructor(private appRef: ApplicationRef,private changeDetectorRef: ChangeDetectorRef) {
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() {
this.item = {};
// 获取存储的数据
(<any> window).courseware.getData((data) => {
this.item.contentObj = {};
const getData = (<any> window).courseware.getData;
getData((data) => {
// console.log("读取数据", data)
if (data) {
this.item = data;
} else {
this.item = {};
}
if ( !this.item.contentObj ) {
this.item.contentObj = {};
}
this.init();
this.changeDetectorRef.markForCheck();
this.changeDetectorRef.detectChanges();
this.refresh();
if(this.dataArray.length>0) {
this.currentSet = 0
}
// this.saveItem()
}, this.KEY);
}
}, this.saveKey);
ngOnChanges() {
}
ngOnDestroy() {
ngOnChanges() {
}
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)
}
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
}
}
handeGridChange(e, item, row, col) {
if(item.text != "" && e.target.value != "") {
item.index = this.currentSet
} else {
item.index = -1;
}
this.saveItem()
}
init() {
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()
}
/**
* 储存图片数据
* @param e
*/
onImageUploadSuccess(e, key) {
handleGirdSizeChange() {
let col = Number(this.size.wh.split("*")[0]);
let row = Number(this.size.wh.split("*")[1]);
this.item[key] = e.url;
this.save();
let _grid = []
for(let i=0; i<row; i++) {
_grid[i] = [];
for(let j=0; j<col; j++) {
_grid[i].push({index: -1, text: ""});
}
}
/**
* 储存音频数据
* @param e
*/
onAudioUploadSuccess(e, key) {
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();
};
this.item[key] = e.url;
this.save();
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 ""
}
getHighlightInput(item) {
if(item.index == this.currentSet) {
return {highLight: true}
} else {
return {highLight: false}
}
}
handleCurrentIndexChange() {
}
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() {
(<any> window).courseware.setData(this.item, null, this.saveKey);
(<any> window).courseware.setData(this.item, null, this.KEY);
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() {
setTimeout(() => {
this.appRef.tick();
}, 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';
interface AirWindow extends Window {
air: any;
curCtx: any;
curImages: any;
}
declare let window: AirWindow;
import TWEEN from "@tweenjs/tween.js";
import simplexNoise from "../../assets/libs/simplex-noise/simplex-noise.min.js"
import { del } from "selenium-webdriver/http";
import construct = Reflect.construct;
class Sprite {
x = 0;
y = 0;
color = '';
color = "";
radius = 0;
alive = false;
margin = 0;
angle = 0;
ctx;
id;
constructor(ctx = null) {
if (!ctx) {
this.ctx = window.curCtx;
this.ctx = window["curCtx"];
} else {
this.ctx = ctx;
}
......@@ -28,17 +23,10 @@ class Sprite {
update($event) {
this.draw();
}
draw() {
}
draw() { }
}
export class MySprite extends Sprite {
_width = 0;
_height = 0;
_anchorX = 0;
......@@ -53,14 +41,6 @@ export class MySprite extends Sprite {
skewX = 0;
skewY = 0;
_shadowFlag = false;
_shadowColor;
_shadowOffsetX = 0;
_shadowOffsetY = 0;
_shadowBlur = 5;
_radius = 0;
children = [this];
childDepandVisible = true;
......@@ -69,209 +49,69 @@ export class MySprite extends Sprite {
img;
_z = 0;
_showRect;
_bitmapFlag = false;
_offCanvas;
_offCtx;
isCircleStyle = false; // 切成圆形
parent;
_maskSpr;
init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) {
if (imgObj) {
this.img = imgObj;
this.width = this.img.width;
this.height = this.img.height;
}
this.anchorX = anchorX;
this.anchorY = anchorY;
}
setShowRect(rect) {
this._showRect = rect;
}
setShadow(offX, offY, blur, color = 'rgba(0, 0, 0, 0.3)') {
this._shadowFlag = true;
this._shadowColor = color;
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
this._shadowBlur = blur;
}
setRadius(r) {
this._radius = r;
}
setMaskSpr(spr) {
this._maskSpr = spr;
this._createOffCtx();
}
_createOffCtx() {
if (!this._offCtx) {
this._offCanvas = document.createElement('canvas'); // 创建一个新的canvas
this.width = this._offCanvas.width = this.width; // 创建一个正好包裹住一个粒子canvas
this.height = this._offCanvas.height = this.height;
this._offCtx = this._offCanvas.getContext('2d');
}
}
update($event = null) {
if (!this.visible && this.childDepandVisible) {
return;
}
this.draw();
}
draw() {
draw() {
this.ctx.save();
this.drawInit();
this.updateChildren();
this.ctx.restore();
}
drawInit() {
this.ctx.translate(this.x, this.y);
this.ctx.rotate(this.rotation * Math.PI / 180);
this.ctx.rotate((this.rotation * Math.PI) / 180);
this.ctx.scale(this.scaleX, this.scaleY);
this.ctx.globalAlpha = this.alpha;
this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0);
}
drawSelf() {
if (this._shadowFlag) {
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
this.ctx.shadowBlur = this._shadowBlur;
this.ctx.shadowColor = this._shadowColor;
} else {
this.ctx.shadowOffsetX = 0;
this.ctx.shadowOffsetY = 0;
this.ctx.shadowBlur = null;
this.ctx.shadowColor = null;
}
if (this._radius) {
const r = this._radius;
const w = this.width;
const h = this.height;
this.ctx.beginPath()
this._roundRect(-w / 2, - h / 2, w, h, r * 1 || 0);
this.ctx.clip();
}
if (this.isCircleStyle) {
this.ctx.beginPath()
this.ctx.arc(0, 0, Math.max(this.width, this.height) / 2, 0, Math.PI * 2, false); // 圆形
this.ctx.clip();
}
if (this.img) {
if (this._showRect) {
const rect = this._showRect;
this.ctx.drawImage(this.img, rect.x, rect.y, rect.width, rect.height, this._offX + rect.x, this._offY + rect.y, rect.width, rect.height);
} else {
if (this._offCtx) {
this._offScreenRender();
} else {
this.ctx.drawImage(this.img, this._offX, this._offY);
}
}
}
}
_offScreenRender() {
this._offCtx.save();
this._offCtx.clearRect(0, 0, this.width, this.height);
this._offCtx.drawImage(this.img, 0, 0);
if (this._maskSpr) {
this._offCtx.globalCompositeOperation = 'destination-in';
this._offCtx.drawImage(this._maskSpr.img, this._maskSpr.x + this._maskSpr._offX - this._offX , this._maskSpr.y + this._maskSpr._offY - this._offY);
}
this.ctx.drawImage(this._offCanvas, this._offX, this._offY);
this._offCtx.restore();
}
_roundRect(x, y, w, h, r) {
const min_size = Math.min(w, h);
if (r > min_size / 2) r = min_size / 2;
// 开始绘制
const ctx = this.ctx;
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
updateChildren() {
if (this.children.length <= 0) {
return;
}
if (this.children.length <= 0) { return; }
for (const child of this.children) {
if (child === this) {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i] === this) {
if (this.visible) {
this.drawSelf();
}
} else {
child.update();
this.children[i].update();
}
}
}
load(url, anchorX = 0.5, anchorY = 0.5) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
}).then(img => {
this.init(img, anchorX, anchorY);
return img;
});
......@@ -288,12 +128,11 @@ export class MySprite extends Sprite {
return a._z - b._z;
});
if (this.childDepandAlpha) {
child.alpha = this.alpha;
}
}
removeChild(child) {
const index = this.children.indexOf(child);
if (index !== -1) {
......@@ -304,29 +143,62 @@ export class MySprite extends Sprite {
removeChildren() {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i]) {
if (this.children[i] !== this) {
if (this.children[i] != this) {
this.children.splice(i, 1);
i --;
i--;
}
}
}
}
_changeChildAlpha(alpha) {
for (const child of this.children) {
if (child !== this) {
child.alpha = alpha;
for (let i = 0; i < this.children.length; i++) {
if (this.children[i] != this) {
this.children[i].alpha = alpha;
}
}
}
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;
set bitmapFlag(v) {
this._bitmapFlag = v;
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;
}
get bitmapFlag() {
return this._bitmapFlag;
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) {
this._alpha = v;
if (this.childDepandAlpha) {
......@@ -364,88 +236,83 @@ export class MySprite extends Sprite {
get anchorY() {
return this._anchorY;
}
refreshAnchorOff() {
this._offX = -this._width * this.anchorX;
this._offY = -this._height * this.anchorY;
}
}
setScaleXY(value) {
this.scaleX = this.scaleY = value;
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
}
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;
if (x < (a - r)) {
x = a - r
}
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};
let c_y1 = Math.sqrt(r * r - (x - a) * (x - a)) + b
let c_y2 = -Math.sqrt(r * r - (x - a) * (x - a)) + b
if (y > c_y1) {
y = c_y1
}
if (y < c_y2) {
y = c_y2
}
this.ctx[i === 0 ? "moveTo" : "lineTo"](x, y);
}
this.ctx.arc(a, b, r, 0, Math.PI);
this.ctx.closePath();
this.ctx.fillStyle = color;
this.ctx.fill();
}
drawSelf() {
super.drawSelf();
this.speedX = 0;
if (new Date().getTime() - this._runTimeCtl > 10) {
this.speedY += 0.02; //每次渲染需要更新波峰波谷值
}
this._runTimeCtl = new Date().getTime()
this.draw_self(this.water_color, "screen", this.height);
}
}
export class ColorSpr extends MySprite {
r = 0;
g = 0;
b = 0;
createGSCanvas() {
if (!this.img) {
return;
}
const rect = this.getBoundingBox();
if (rect.width <= 1 || rect.height <= 1) {
return;
}
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for ( let i = 0; i < c.height; i++) {
for ( let j = 0; j < c.width; j++) {
const x = (i * 4) * c.width + ( j * 4 );
for (let i = 0; i < c.height; i++) {
for (let j = 0; j < c.width; j++) {
const x = i * 4 * c.width + j * 4;
const r = c.data[x];
const g = c.data[x + 1];
const b = c.data[x + 2];
......@@ -454,88 +321,61 @@ export class ColorSpr extends MySprite {
c.data[x + 1] = this.g;
c.data[x + 2] = this.b;
// c.data[x] = c.data[x + 1] = c.data[x + 2] = (r + g + b) / 3 ;
// // c.data[x + 3] = 255;
}
}
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
}
drawSelf() {
super.drawSelf();
this.createGSCanvas();
}
}
export class GrayscaleSpr extends MySprite {
grayScale = 120;
createGSCanvas() {
if (!this.img) {
return;
}
const rect = this.getBoundingBox();
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for ( let i = 0; i < c.height; i++) {
for ( let j = 0; j < c.width; j++) {
const x = (i * 4) * c.width + ( j * 4 );
for (let i = 0; i < c.height; i++) {
for (let j = 0; j < c.width; j++) {
const x = i * 4 * c.width + j * 4;
const r = c.data[x];
const g = c.data[x + 1];
const b = c.data[x + 2];
// const a = c.data[x + 3];
c.data[x] = c.data[x + 1] = c.data[x + 2] = this.grayScale; // (r + g + b) / 3;
// c.data[x + 3] = 255;
}
}
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
}
drawSelf() {
super.drawSelf();
this.createGSCanvas();
}
}
export class BitMapLabel extends MySprite {
labelArr;
baseUrl;
setText(data, text) {
this.labelArr = [];
const labelArr = [];
const tmpArr = text.split('');
const tmpArr = text.split("");
let totalW = 0;
let h = 0;
for (const tmp of tmpArr) {
for (let i = 0; i < tmpArr.length; i++) {
const label = new MySprite(this.ctx);
label.init(data[tmp], 0);
label.init(data[tmpArr[i]], 0);
this.addChild(label);
labelArr.push(label);
......@@ -543,47 +383,44 @@ export class BitMapLabel extends MySprite {
h = label.height;
}
this.width = totalW;
this.height = h;
let offX = -totalW / 2;
for (const label of labelArr) {
label.x = offX;
offX += label.width;
for (let i = 0; i < labelArr.length; i++) {
labelArr[i].x = offX;
offX += labelArr[i].width;
}
this.labelArr = labelArr;
}
}
export class Label extends MySprite {
text: string;
text: String;
// fontSize:String = '40px';
fontName = 'Verdana';
textAlign = 'left';
fontName: String = "Verdana";
textAlign: String = "left";
fontSize = 40;
fontColor = '#000000';
fontColor = "#000000";
fontWeight = 900;
_maxWidth;
maxWidth;
outline = 0;
outlineColor = '#ffffff';
outlineColor = "#ffffff";
// _shadowFlag = false;
// _shadowColor;
// _shadowOffsetX;
// _shadowOffsetY;
// _shadowBlur;
maxSingalLineWidth = 0;
baseY = 0
warpLineHeight = 0;
_shadowFlag = false;
_shadowColor;
_shadowOffsetX;
_shadowOffsetY;
_shadowBlur;
_outlineFlag = false;
_outLineWidth;
_outLineColor;
_warpLineY = 0;
constructor(ctx = null) {
super(ctx);
......@@ -591,25 +428,45 @@ export class Label extends MySprite {
}
refreshSize() {
this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight;
this._width = this.ctx.measureText(this.text).width;
this._height = this.fontSize;
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) {
this._maxWidth = w;
this.maxWidth = w;
this.refreshSize();
if (this.width >= w) {
this.scaleX *= w / this.width;
......@@ -618,7 +475,6 @@ export class Label extends MySprite {
}
show(callBack = null) {
this.visible = true;
if (this.alpha >= 1) {
......@@ -628,7 +484,7 @@ export class Label extends MySprite {
const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.onComplete(function () {
if (callBack) {
callBack();
}
......@@ -636,49 +492,42 @@ export class Label extends MySprite {
.start(); // Start the tween immediately.
}
// setShadow(offX = 0, offY = 2, blur = 2, color = 'rgba(0, 0, 0, 0.2)') {
//
// this._shadowFlag = true;
// this._shadowColor = color;
// // 将阴影向右移动15px,向上移动10px
// this._shadowOffsetX = 5;
// this._shadowOffsetY = 5;
// // 轻微模糊阴影
// this._shadowBlur = 5;
// }
setOutline(width = 5, color = '#ffffff') {
setShadow(offX = 2, offY = 2, blur = 2, color = "rgba(0, 0, 0, 0.2)") {
this._shadowFlag = true;
this._shadowColor = color;
// 将阴影向右移动15px,向上移动10px
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
// 轻微模糊阴影
this._shadowBlur = blur;
}
setOutline(width = 5, color = "#ffffff") {
this._outlineFlag = true;
this._outLineWidth = width;
this._outLineColor = color;
}
drawText() {
// console.log('in drawText', this.text);
if (!this.text) { return; }
// if (this._shadowFlag) {
//
// this.ctx.shadowColor = this._shadowColor;
// // 将阴影向右移动15px,向上移动10px
// this.ctx.shadowOffsetX = this._shadowOffsetX;
// this.ctx.shadowOffsetY = this._shadowOffsetY;
// // 轻微模糊阴影
// this.ctx.shadowBlur = this._shadowBlur;
// }
if (!this.text) {
return;
}
if (this._shadowFlag) {
this.ctx.shadowColor = this._shadowColor;
// 将阴影向右移动15px,向上移动10px
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
// 轻微模糊阴影
this.ctx.shadowBlur = this._shadowBlur;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight;
if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor;
......@@ -687,61 +536,152 @@ export class Label extends MySprite {
this.ctx.fillStyle = this.fontColor;
if (this.outline > 0) {
this.ctx.lineWidth = this.outline;
this.ctx.strokeStyle = this.outlineColor;
this.ctx.strokeText(this.text, 0, 0);
}
// 当maxSingalLineWidth不为0时,对数据进行换行处理
if (this.maxSingalLineWidth !== 0) {
var words = this.text.split(' ');
var line = '';
this._warpLineY = 0;
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = this.ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > this.maxSingalLineWidth && n > 0) {
this.ctx.fillText(line, 0, this._warpLineY);
line = words[n] + ' ';
this._warpLineY += this.fontSize;
}
else {
line = testLine;
}
}
this.y = this.baseY // + this._warpLineY
this.ctx.fillText(line, 0, this._warpLineY);
} else {
this.ctx.fillText(this.text, 0, 0);
}
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class ShapeRectNew extends MySprite {
radius = 0;
fillColor = '#ffffff';
strokeColor = '#000000';
fill = true;
stroke = false;
lineWidth = 1;
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
drawShape() {
const ctx = this.ctx;
const width = this.width;
const height = this.height;
const radius = this.radius;
ctx.save();
ctx.beginPath(0);
// 从右下角顺时针绘制,弧度从0到1/2PI
ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
// 矩形下边线
ctx.lineTo(radius, height);
// 左下角圆弧,弧度从1/2PI到PI
ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
// 矩形左边线
ctx.lineTo(0, radius);
// 左上角圆弧,弧度从PI到3/2PI
ctx.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
// 上边线
ctx.lineTo(width - radius, 0);
// 右上角圆弧
ctx.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
// 右边线
ctx.lineTo(width, height - radius);
ctx.closePath();
if (this.fill) {
ctx.fillStyle = this.fillColor;
ctx.fill();
}
if (this.stroke) {
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.strokeColor;
ctx.stroke();
}
ctx.restore();
}
drawSelf() {
super.drawSelf();
this.drawText();
this.drawShape();
}
}
export class RichTextOld extends Label {
textArr = [];
fontSize = 40;
setText(text: string, words) {
let newText = text;
for (const word of words) {
for (let i = 0; i < words.length; i++) {
const word = words[i];
const re = new RegExp(word, 'g');
newText = newText.replace( re, `#${word}#`);
const re = new RegExp(word, "g");
newText = newText.replace(re, `#${word}#`);
// newText = newText.replace(word, `#${word}#`);
}
this.textArr = newText.split('#');
this.textArr = newText.split("#");
this.text = newText;
// this.setSize();
}
refreshSize() {
this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight;
let curX = 0;
for (const text of this.textArr) {
const w = this.ctx.measureText(text).width;
for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width;
curX += w;
}
......@@ -750,12 +690,9 @@ export class RichTextOld extends Label {
this.refreshAnchorOff();
this.ctx.restore();
}
show(callBack = null) {
// console.log(' in show ');
this.visible = true;
// this.alpha = 0;
......@@ -763,186 +700,119 @@ export class RichTextOld extends Label {
const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.onComplete(function () {
if (callBack) {
callBack();
}
})
.start(); // Start the tween immediately.
}
drawText() {
// console.log('in drawText', this.text);
if (!this.text) { return; }
if (!this.text) {
return;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.textBaseline = "middle";
this.ctx.fontWeight = 900;
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = '#ffffff';
this.ctx.strokeStyle = "#ffffff";
// this.ctx.strokeText(this.text, 0, 0);
this.ctx.fillStyle = '#000000';
this.ctx.fillStyle = "#000000";
// this.ctx.fillText(this.text, 0, 0);
let curX = 0;
for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width;
if ((i + 1) % 2 === 0) {
this.ctx.fillStyle = '#c8171e';
if ((i + 1) % 2 == 0) {
this.ctx.fillStyle = "#c8171e";
} else {
this.ctx.fillStyle = '#000000';
this.ctx.fillStyle = "#000000";
}
this.ctx.fillText(this.textArr[i], curX, 0);
curX += w;
}
}
}
export class RichText extends Label {
disH = 30;
offW = 10;
constructor(ctx?: any) {
constructor(ctx = null) {
super(ctx);
// this.dataArr = dataArr;
}
drawText() {
if (!this.text) {
return;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight;
this.ctx.fillStyle = this.fontColor;
const selfW = this.width * this.scaleX;
const chr = this.text.split(' ');
let temp = '';
const chr = this.text.split(" ");
let temp = "";
const row = [];
const w = selfW - this.offW * 2;
const w = selfW - 80;
const disH = (this.fontSize + this.disH) * this.scaleY;
for (const c of chr) {
if (this.ctx.measureText(temp).width < w && this.ctx.measureText(temp + (c)).width <= w) {
temp += ' ' + c;
for (let a = 0; a < chr.length; a++) {
if (
this.ctx.measureText(temp).width < w &&
this.ctx.measureText(temp + chr[a]).width <= w
) {
temp += " " + chr[a];
} else {
row.push(temp);
temp = ' ' + c;
temp = " " + chr[a];
}
}
row.push(temp);
const x = 0;
const y = -row.length * disH / 2;
const y = (-row.length * disH) / 2;
// for (let b = 0 ; b < row.length; b++) {
// this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
// }
if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor;
for (let b = 0 ; b < row.length; b++) {
this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
for (let b = 0; b < row.length; b++) {
this.ctx.strokeText(row[b], x, y + (b + 1) * disH); // 每行字体y坐标间隔20
}
// this.ctx.strokeText(this.text, 0, 0);
}
// this.ctx.fillStyle = '#ff7600';
for (let b = 0 ; b < row.length; b++) {
this.ctx.fillText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
for (let b = 0; b < row.length; b++) {
this.ctx.fillText(row[b], x, y + (b + 1) * disH); // 每行字体y坐标间隔20
}
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class LineRect extends MySprite {
lineColor = '#ffffff';
lineWidth = 10;
setSize(w, h) {
this.width = w;
this.height = h;
}
drawLine() {
this.ctx.beginPath();
this.ctx.moveTo(this._offX, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY + this.height);
this.ctx.lineTo(this._offX, this._offY + this.height);
this.ctx.closePath();
this.ctx.lineWidth = this.lineWidth;
// this.ctx.fillStyle = "rgb(2,33,42)"; //指定填充颜色
// this.ctx.fill(); //对多边形进行填充
this.ctx.strokeStyle = this.lineColor; // "#ffffff";
this.ctx.stroke();
}
drawSelf() {
super.drawSelf();
this.drawLine();
}
}
export class ShapeRect extends MySprite {
fillColor = '#FF0000';
fillColor = "#FF0000";
setSize(w, h) {
this.width = w;
......@@ -953,145 +823,79 @@ export class ShapeRect extends MySprite {
}
drawShape() {
this.ctx.fillStyle = this.fillColor;
this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class ShapeCircle extends MySprite {
fillColor = '#FF0000';
fillColor = "#FFFF00";
radius = 0;
startRadian = 0;
endRadian = 180;
strokeLineWidth = 5;
strokeColor = "#702dee";
drawType = "fill"
counterclockwise = false; // false 逆时针 true 顺时针
shadowColor = "rgba(0,0,0,0)"
shadowOffsetX = 0;
shadowOffsetY = 0;
setRadius(r) {
this.anchorX = this.anchorY = 0.5;
this.radius = r;
this.width = r * 2;
this.height = r * 2;
}
drawShape() {
switch (this.drawType) {
case "stroke":
this.ctx.beginPath();
this.ctx.strokeStyle = this.strokeColor;
this.ctx.lineWidth = this.strokeLineWidth
this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian, this.counterclockwise);
this.ctx.stroke()
break;
default:
this.ctx.beginPath();
this.ctx.fillStyle = this.fillColor;
this.ctx.arc(0, 0, this.radius, 0, angleToRadian(360));
this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian);
this.ctx.shadowColor = this.shadowColor
this.ctx.shadowOffsetX = this.shadowOffsetX
this.ctx.shadowOffsetY = this.shadowOffsetY
this.ctx.fill();
break;
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class ShapeRectNew extends MySprite {
radius = 0;
fillColor = '#ffffff';
strokeColor = '#000000';
fill = true;
stroke = false;
lineWidth = 1;
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
drawShape() {
const ctx = this.ctx;
const width = this.width;
const height = this.height;
const radius = this.radius;
ctx.save();
ctx.beginPath(0);
// 从右下角顺时针绘制,弧度从0到1/2PI
ctx.arc(width - radius + 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() {
super.drawSelf();
this.drawShape();
}
}
export class MyAnimation extends MySprite {
export class MyAnimation extends MySprite {
frameArr = [];
frameIndex = 0;
playFlag = false;
lastDateTime;
curDelay = 0;
loop = false;
playEndFunc;
delayPerUnit = 0.07;
delayPerUnit = 1;
restartFlag = false;
reverseFlag = false;
addFrameByImg(img) {
const spr = new MySprite(this.ctx);
spr.init(img);
this._refreshSize(img);
......@@ -1105,10 +909,8 @@ export class MyAnimation extends MySprite {
}
addFrameByUrl(url) {
const spr = new MySprite(this.ctx);
spr.load(url).then(img => {
this._refreshSize(img);
});
spr.visible = false;
......@@ -1119,18 +921,15 @@ export class MyAnimation extends MySprite {
this.frameArr[this.frameIndex].visible = true;
}
_refreshSize(img: any) {
if (this.width < img.width) {
this.width = img.width;
_refreshSize(img) {
if (this.width < img["width"]) {
this.width = img["width"];
}
if (this.height < img.height) {
this.height = img.height;
if (this.height < img["height"]) {
this.height = img["height"];
}
}
play() {
this.playFlag = true;
this.lastDateTime = new Date().getTime();
......@@ -1140,13 +939,11 @@ export class MyAnimation extends MySprite {
this.playFlag = false;
}
replay() {
this.restartFlag = true;
this.play();
}
reverse() {
this.reverseFlag = !this.reverseFlag;
this.frameArr.reverse();
......@@ -1154,29 +951,26 @@ export class MyAnimation extends MySprite {
}
showAllFrame() {
for (const frame of this.frameArr ) {
frame.alpha = 1;
for (let i = 0; i < this.frameArr.length; i++) {
this.frameArr[i].alpha = 1;
}
}
hideAllFrame() {
for (const frame of this.frameArr) {
frame.alpha = 0;
for (let i = 0; i < this.frameArr.length; i++) {
this.frameArr[i].alpha = 0;
}
}
playEnd() {
this.playFlag = false;
this.curDelay = 0;
this.frameArr[this.frameIndex].visible = true;
if (this.playEndFunc) {
const func = this.playEndFunc;
this.playEndFunc();
this.playEndFunc = null;
func();
}
}
......@@ -1185,7 +979,7 @@ export class MyAnimation extends MySprite {
this.frameArr[this.frameIndex].visible = false;
}
this.frameIndex ++;
this.frameIndex++;
if (this.frameIndex >= this.frameArr.length) {
if (this.loop) {
this.frameIndex = 0;
......@@ -1193,21 +987,16 @@ export class MyAnimation extends MySprite {
this.restartFlag = false;
this.frameIndex = 0;
} else {
this.frameIndex -- ;
this.frameIndex--;
this.playEnd();
return;
}
}
this.frameArr[this.frameIndex].visible = true;
}
_updateDelay(delay) {
this.curDelay += delay;
if (this.curDelay < this.delayPerUnit) {
return;
......@@ -1217,7 +1006,9 @@ export class MyAnimation extends MySprite {
}
_updateLastDate() {
if (!this.playFlag) { return; }
if (!this.playFlag) {
return;
}
let delay = 0;
if (this.lastDateTime) {
......@@ -1231,26 +1022,18 @@ export class MyAnimation extends MySprite {
super.update($event);
this._updateLastDate();
}
}
// --------=========== util func =============-------------
export function tweenChange(item, obj, time = 0.8, callBack = null, easing = null, update = null) {
const tween = createTween(item, obj, time, callBack, easing, update)
tween.start();
return tween;
}
export function createTween(item, obj, time = 0.8, callBack = null, easing = null, update = null) {
export function tweenChange(
item,
obj,
time = 0.8,
callBack = null,
easing = null,
update = null
) {
const tween = new TWEEN.Tween(item).to(obj, time * 1000);
if (callBack) {
......@@ -1262,47 +1045,29 @@ export function createTween(item, obj, time = 0.8, callBack = null, easing = nul
tween.easing(easing);
}
if (update) {
tween.onUpdate( (a, b) => {
tween.onUpdate((a, b) => {
update(a, b);
});
}
return tween;
}
export function tweenQueue(arr) {
const showOneTween = () => {
const tween = arr.shift();
if (arr.length > 0) {
tween.onComplete( () => {
showOneTween();
});
}
tween.start();
};
showOneTween();
return tween;
}
export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = null, loop = false) {
export function rotateItem(
item,
rotation,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
} else if (loop) {
const speed = (rotation - item.rotation) / time;
tween.onComplete(() => {
item.rotation %= 360;
rotateItem(item, item.rotation + speed * time, time, null, easing, true);
});
}
if (easing) {
tween.easing(easing);
}
......@@ -1310,11 +1075,17 @@ export function rotateItem(item, rotation, time = 0.8, callBack = null, easing =
tween.start();
}
export function scaleItem(item, scale, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ scaleX: scale, scaleY: scale}, time * 1000);
export function scaleItem(
item,
scale,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to(
{ scaleX: scale, scaleY: scale },
time * 1000
);
if (callBack) {
tween.onComplete(() => {
......@@ -1329,10 +1100,15 @@ export function scaleItem(item, scale, time = 0.8, callBack = null, easing = nul
return tween;
}
export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ x, y}, time * 1000);
export function moveItem(
item,
x,
y,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to({ x, y }, time * 1000);
if (callBack) {
tween.onComplete(() => {
......@@ -1348,36 +1124,26 @@ export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null)
return tween;
}
export function endShow(item, s = 1) {
item.scaleX = item.scaleY = 0;
item.alpha = 0;
const tween = new TWEEN.Tween(item)
.to({ alpha: 1, scaleX: s, scaleY: s }, 800)
.easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
})
.onComplete(function () { })
.start();
}
export function hideItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha === 0) {
if (item.alpha == 0) {
return;
}
const tween = new TWEEN.Tween(item)
.to({alpha: 0}, time * 1000)
.to({ alpha: 0 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.onComplete(function () {
if (callBack) {
callBack();
}
......@@ -1390,10 +1156,8 @@ export function hideItem(item, time = 0.8, callBack = null, easing = null) {
tween.start();
}
export function showItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha === 1) {
if (item.alpha == 1) {
if (callBack) {
callBack();
}
......@@ -1402,9 +1166,9 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) {
item.visible = true;
const tween = new TWEEN.Tween(item)
.to({alpha: 1}, time * 1000)
.to({ alpha: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.onComplete(function () {
if (callBack) {
callBack();
}
......@@ -1417,14 +1181,17 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) {
tween.start();
}
export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = null) {
export function alphaItem(
item,
alpha,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item)
.to({alpha}, time * 1000)
.to({ alpha: alpha }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.onComplete(function () {
if (callBack) {
callBack();
}
......@@ -1437,14 +1204,11 @@ export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = nul
tween.start();
}
export function showStar(item, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item)
.to({alpha: 1, scale: 1}, time * 1000)
.to({ alpha: 1, scale: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => {
.onComplete(function () {
if (callBack) {
callBack();
}
......@@ -1457,97 +1221,103 @@ export function showStar(item, time = 0.8, callBack = null, easing = null) {
tween.start();
}
export function randomSortByArr(arr) {
const newArr = [];
const tmpArr = arr.concat();
while (tmpArr.length > 0) {
const randomIndex = Math.floor( tmpArr.length * Math.random() );
const randomIndex = Math.floor(tmpArr.length * Math.random());
newArr.push(tmpArr[randomIndex]);
tmpArr.splice(randomIndex, 1);
}
return newArr;
}
export function radianToAngle(radian) {
return radian * 180 / Math.PI;
return (radian * 180) / Math.PI;
// 角度 = 弧度 * 180 / Math.PI;
}
export function angleToRadian(angle) {
return angle * Math.PI / 180;
return (angle * Math.PI) / 180;
// 弧度= 角度 * Math.PI / 180;
}
export function getPosByAngle(angle, len) {
const radian = angle * Math.PI / 180;
const radian = (angle * Math.PI) / 180;
const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len;
return {x, y};
return { x, y };
}
export function getAngleByPos(px, py, mx, my) {
const x = Math.abs(px - mx);
const y = Math.abs(py - my);
const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
const cos = y / z;
const radina = Math.acos(cos); // 用反三角函数求弧度
let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度
let angle = Math.floor((180 / (Math.PI / radina)) * 100) / 100; // 将弧度转换成角度
if (mx > px && my > py) {// 鼠标在第四象限
if (mx > px && my > py) {
// 鼠标在第四象限
angle = 180 - angle;
}
if (mx === px && my > py) {// 鼠标在y轴负方向上
if (mx === px && my > py) {
// 鼠标在y轴负方向上
angle = 180;
}
if (mx > px && my === py) {// 鼠标在x轴正方向上
if (mx > px && my === py) {
// 鼠标在x轴正方向上
angle = 90;
}
if (mx < px && my > py) {// 鼠标在第三象限
if (mx < px && my > py) {
// 鼠标在第三象限
angle = 180 + angle;
}
if (mx < px && my === py) {// 鼠标在x轴负方向
if (mx < px && my === py) {
// 鼠标在x轴负方向
angle = 270;
}
if (mx < px && my < py) {// 鼠标在第二象限
if (mx < px && my < py) {
// 鼠标在第二象限
angle = 360 - angle;
}
// console.log('angle: ', angle);
return angle;
}
export function removeItemFromArr(arr, item) {
const index = arr.indexOf(item);
if (index !== -1) {
if (index != -1) {
arr.splice(index, 1);
}
}
export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = 1, callBack = null, easing = null) {
export function circleMove(
item,
x0,
y0,
time = 2,
addR = 360,
xPer = 1,
yPer = 1,
callBack = null,
easing = null
) {
const r = getPosDistance(item.x, item.y, x0, y0);
let a = getAngleByPos(item.x, item.y, x0, y0);
a += 90;
const obj = {r, a};
const obj = { r, a };
item._circleAngle = a;
const targetA = a + addR;
const tween = new TWEEN.Tween(item).to({_circleAngle: targetA}, time * 1000);
const tween = new TWEEN.Tween(item).to(
{ _circleAngle: targetA },
time * 1000
);
if (callBack) {
tween.onComplete(() => {
......@@ -1558,14 +1328,13 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer =
tween.easing(easing);
}
tween.onUpdate( (item, progress) => {
tween.onUpdate((item, progress) => {
// console.log(item._circleAngle);
const r = obj.r;
const a = item._circleAngle;
const x = x0 + r * xPer * Math.cos(a * Math.PI / 180);
const y = y0 + r * yPer * Math.sin(a * Math.PI / 180);
const x = x0 + r * xPer * Math.cos((a * Math.PI) / 180);
const y = y0 + r * yPer * Math.sin((a * Math.PI) / 180);
item.x = x;
item.y = y;
......@@ -1576,16 +1345,14 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer =
tween.start();
}
export function getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx;
const _y = ey - sy;
const len = Math.sqrt( Math.pow(_x, 2) + Math.pow(_y, 2) );
const len = Math.sqrt(Math.pow(_x, 2) + Math.pow(_y, 2));
return len;
}
export function delayCall(second, callback) {
export function delayCall(callback, second) {
const tween = new TWEEN.Tween(this)
.delay(second * 1000)
.onComplete(() => {
......@@ -1596,46 +1363,14 @@ export function delayCall(second, callback) {
.start();
}
export function formatTime(fmt, date) {
// "yyyy-MM-dd HH:mm:ss";
const o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); }
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1)
? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return fmt;
}
export function getMinScale(item, maxW, maxH = null) {
if (!maxH) {
maxH = maxW;
}
const sx = maxW / item.width;
const sy = maxH / item.height;
export function getMinScale(item, maxLen) {
const sx = maxLen / item.width;
const sy = maxLen / item.height;
const minS = Math.min(sx, sy);
return minS;
}
export function jelly(item, time = 0.7) {
if (item.jellyTween) {
TWEEN.remove(item.jellyTween);
}
......@@ -1651,10 +1386,16 @@ export function jelly(item, time = 0.7) {
return;
}
const data = arr[index];
const t = tweenChange(item, {scaleX: data[0], scaleY: data[1]}, data[2], () => {
index ++;
const t = tweenChange(
item,
{ scaleX: data[0], scaleY: data[1] },
data[2],
() => {
index++;
run();
}, TWEEN.Easing.Sinusoidal.InOut);
},
TWEEN.Easing.Sinusoidal.InOut
);
item.jellyTween = t;
};
......@@ -1663,60 +1404,24 @@ export function jelly(item, time = 0.7) {
[baseSX * 0.98, baseSY * 1.02, t * 2],
[baseSX * 1.02, baseSY * 0.98, t * 2],
[baseSX * 0.99, baseSY * 1.01, t * 2],
[baseSX * 1.0, baseSY * 1.0, t * 2],
];
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],
[baseSX * 1.0, baseSY * 1.0, t * 2]
];
item.setScaleXY(0);
run();
}
export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen = 80, showTime = 0.4) {
for (let i = 0; i < num; i ++) {
/**
* 烟花爆炸效果动画
* @param img 颗粒的图片
* @param pos 爆点的坐标
* @param parent 必须传一个父类
*/
export function showPopParticle(img, pos, parent) {
const num = 20;
const maxLen = 100;
const minLen = 40;
for (let i = 0; i < num; i++) {
const particle = new MySprite();
particle.init(img);
particle.x = pos.x;
......@@ -1726,8 +1431,8 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen
const randomR = 360 * Math.random();
particle.rotation = randomR;
const randomS = 0.3 + Math.random() * 0.7;
particle.setScaleXY(randomS * 0.3);
const randomS = 0.5 + Math.random() * 0.5;
particle.setScaleXY(randomS);
const randomX = Math.random() * 20 - 10;
particle.x += randomX;
......@@ -1735,39 +1440,23 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen
const randomY = Math.random() * 20 - 10;
particle.y += randomY;
const randomL = minLen + Math.random() * (maxLen - minLen);
const randomL = minLen + Math.random() * maxLen;
const randomA = 360 * Math.random();
const randomT = getPosByAngle(randomA, randomL);
moveItem(particle, particle.x + randomT.x, particle.y + randomT.y, showTime, () => {
}, TWEEN.Easing.Exponential.Out);
// scaleItem(particle, 0, 0.6, () => {
//
// });
scaleItem(particle, randomS, 0.6, () => {
}, TWEEN.Easing.Exponential.Out);
setTimeout(() => {
hideItem(particle, 0.4, () => {
}, TWEEN.Easing.Cubic.In);
}, showTime * 0.5 * 1000);
moveItem(
particle,
particle.x + randomT.x,
particle.y + randomT.y,
0.4,
() => { },
TWEEN.Easing.Exponential.Out
);
scaleItem(particle, 0, 0.6, () => { });
}
}
export function shake(item, time = 0.5, callback = null, rate = 1) {
if (item.shakeTween) {
return;
}
......@@ -1779,73 +1468,104 @@ export function shake(item, time = 0.5, callback = null, rate = 1) {
const baseY = item.y;
const easing = TWEEN.Easing.Sinusoidal.InOut;
const move4 = () => {
moveItem(item, baseX, baseY, time / 4, () => {
moveItem(
item,
baseX,
baseY,
time / 4,
() => {
item.shakeTween = false;
if (callback) {
callback();
}
}, easing);
},
easing
);
};
const move3 = () => {
moveItem(item, baseX + offX / 4, baseY + offY / 4, time / 4, () => {
moveItem(
item,
baseX + offX / 4,
baseY + offY / 4,
time / 4,
() => {
move4();
}, easing);
},
easing
);
};
const move2 = () => {
moveItem(item, baseX - offX / 4 * 3, baseY - offY / 4 * 3, time / 4, () => {
moveItem(
item,
baseX - (offX / 4) * 3,
baseY - (offY / 4) * 3,
time / 4,
() => {
move3();
}, easing);
},
easing
);
};
const move1 = () => {
moveItem(item, baseX + offX, baseY + offY, time / 7.5, () => {
moveItem(
item,
baseX + offX,
baseY + offY,
time / 8,
() => {
move2();
}, easing);
},
easing
);
};
move1();
}
export function getMaxScale(item, maxW, maxH) {
const sx = maxW / item.width;
const sy = maxH / item.height;
const maxS = Math.max(sx, sy);
return maxS;
}
// --------------- custom class --------------------
export function showBlingBling(starImg, rectArea, parent, mapScale = 1, num = 30, disTime = 0.1, showTime = 3) {
const timeId = setInterval(() => {
showBlingStar(starImg, num, rectArea, parent, mapScale);
}, disTime * 1000);
setTimeout(() => {
clearInterval(timeId);
}, showTime * 1000);
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;
this.width = this.element.videoWidth;
this.height = this.element.videoHeight;
const randomS = (0.1 + Math.random() * 0.8) * mapScale;
star.setScaleXY(1);
this.element.currentTime = 0.01;
}
parent.addChild(star);
drawSelf() {
super.drawSelf();
scaleItem(star, randomS, 0.3, () => {
this.ctx.drawImage(this.element, 0, 0, this.width, this.height);
}
}
setTimeout(() => {
scaleItem(star, 0, 0.3, () => {
parent.removeChild(star);
});
// --------------- custom class --------------------
}, 100 + Math.random() * 200);
});
}
}
\ No newline at end of file
.game-container {
width: 100%;
height: 100%;
background: #ffffff;
background-size: cover;
}
#canvas {
}
@font-face
{
font-family: 'BRLNSDB';
src: url("../../assets/font/BRLNSDB.TTF") ;
}
.game-container {
width: 100%;
height: 100%;
//background-image: url("/assets/play/listen-read-circle/bg.jpg");
background: #ffffff;
background-repeat: no-repeat;
background-size: cover;
}
.read-and-point-copy {
width: 500px;
height: 85px;
object-fit: contain;
text-shadow: 0 6px 4px rgba(0, 0, 0, 0.5), 0 3px 0 #fffecc;
font-family: Questrian;
font-size: 72px;
font-weight: normal;
font-stretch: normal;
font-style: normal;
line-height: normal;
letter-spacing: normal;
color: #f8e424;
}
.read-and-point-copy .text-style-1 {
font-size: 48px;
}
.read-and-point-copy .text-style-2 {
font-size: 64px;
}
// @font-face{
// font-family: 'BRLNSDB';
// src: url("../../assets/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 {
MySprite,
RichText,
getMinScale,
ShapeRect,
ShapeCircle,
tweenChange,
randomSortByArr,
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';
import {res, resAudio} from './resources';
@Component({
selector: "app-play",
templateUrl: "./play.component.html",
styleUrls: ["./play.component.scss"]
})
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
export class PlayComponent implements OnInit, OnDestroy {
import TWEEN from '@tweenjs/tween.js';
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()
}
// 映射预加载图片[网路]资源 返回包含图片路径的数组
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;
@ViewChild('wrap', {static: true }) wrap: ElementRef;
startGame(){
// 数据
data;
}
ctx;
restartGame(){
// this.cleanGameVar()
this.startGame()
}
canvasWidth = 1280; // canvas实际宽度
canvasHeight = 720; // canvas实际高度
initBackground() {
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 资源预设宽度
canvasBaseH = 720; // canvas 资源预设高度
let mask = this.g_cartoon.createCartoonElementImageFunc("background_mask", "bg_main_mask", (w, h)=>{
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坐标
my; // 点击y坐标
initTitle() {
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)
}
// 资源
rawImages = new Map(res);
rawAudios = new Map(resAudio);
initQuestion() {
let element = this.g_cartoon.createCartoonElementImageFunc("question_container", "bg_question", (w, h)=>{
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;
winResizeEventStream = new Subject();
let btnPre = this.g_cartoon.createCartoonElementImageFunc("question_pre", "btn_pre", (w, h)=>{
return {
sx: 136 / w,
sy: 136 / h,
}
}, (w, h)=>{
return {
x: -1010,
y: 0
}
})
audioObj = {};
let labelIndex = this.g_cartoon.createCartoonElementLabelFunc("question_index", "", "Aileron-Bold", "#3e9b31", 48, (w, h)=>{
return {
x: 0,
y: -110,
}
})
labelIndex.ref.text = "Across 1"
renderArr;
mapScale = 1;
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"
canvasLeft;
canvasTop;
saveKey = 'test_0011';
element.ref.addChild(labelIndex.ref)
element.ref.addChild(questionText.ref)
element.ref.addChild(btnNext.ref)
element.ref.addChild(btnPre .ref)
this.render(element.ref)
}
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)
btnLeft;
btnRight;
pic1;
pic2;
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
}
})
canTouch = true;
this.render(partBG.ref)
this.render(element.ref)
}
curPic;
initTitle_Main(){
let labelWidth = 0
let text = this.g_cartoon.createCartoonElementLabelFunc("main-title", this.g_formData.title.mainText, "FuturaBT Medium", "#000000", 36, (w, h)=>{
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)
@HostListener('window:resize', ['$event'])
onResize(event) {
this.winResizeEventStream.next();
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
}
})
text.ref.x = this.g_partTitle_x + 60 * this.g_mapScale
text.ref.textAlign = "left"
ngOnInit() {
this.subscribeMapDownEvent(background.id, ()=>{
this.g_cartoon.stopAllAudio()
this.g_cartoon.playAudio(this.g_formData.title.mainTextAudio_url);
this.resetLongAudio();
this.g_enableMapDown = true;
})
this.data = {};
this.render(background.ref)
this.render(text.ref)
}
// 获取数据
const getData = (<any> window).courseware.getData;
getData((data) => {
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]
})
}
if (data && typeof data == 'object') {
this.data = data;
let numIcon = this.g_cartoon.createCartoonElementImageFunc(`card_${i}_numIcon`, `num_icon_${i+1}`, (w, h)=>{
return {
sx: 60 / w,
sy: 60 / h,
}
// console.log('data:' , data);
}, (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)
// 初始化 各事件监听
this.initListener();
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)
// 若无数据 则为预览模式 需要填充一些默认数据用来显示
this.initDefaultData();
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)
// 初始化 音频资源
this.initAudio();
// 初始化 图片资源
this.initImg();
// 开始预加载资源
this.load();
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)
}, this.saveKey);
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.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;
}
})
ngOnDestroy() {
window['curCtx'] = null;
window.cancelAnimationFrame(this.animationId);
this.cleanAudio();
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;
}
})
cleanAudio() {
if (this.audioObj) {
for (const key in this.audioObj) {
this.audioObj[key].pause();
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)
});
}
initAudioPlayerAll(){
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,
}
})
element.ref.setScaleXY(0)
let play = this.g_cartoon.createCartoonElementImageFunc(`audio-all-play`, "icon_paly", (w, h)=>{
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)=>{
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)
load() {
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 = ()=>{
if(!element.audio){
return
}
element.isPlaying = false;
element.audio.pause()
element.playIcon.ref.visible = true;
element.pauseIcon.ref.visible = false;
}
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;
})
if(this.g_formData.long_audio.audio_url) {
element.out()
}
this.render(element.ref, 99)
}
resetLongAudio(){
let audio = this.g_cartoon.getCartoonElement(`audio-all`)
if(audio.enable){
audio.pause()
}
}
// --------------------------------------------------
// -------------- 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 = {};
}
this.initDefaultData();
this.initAudio();
this.initImg();
// 预加载资源
this.loadResources().then(() => {
window["air"].hideAirClassLoading(this.saveKey, this.data);
this.init();
this.g_cartoon.loadResources().then(() => {
window["air"].hideAirClassLoading(this.g_KEY, this.g_data);
this.initSystem();
this.update();
this.systemReady()
});
this.initListener();
}, this.g_KEY);
}
// ----------------------------------
// 初始化默认数据
// ----------------------------------
initDefaultData() {
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)
}
}
init() {
this.initCtx();
this.initData();
this.initView();
// ----------------------------------
// 初始化音乐
// ----------------------------------
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 );
});
initCtx() {
this.canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight;
this.canvas.nativeElement.width = this.wrap.nativeElement.clientWidth;
this.canvas.nativeElement.height = this.wrap.nativeElement.clientHeight;
// 添加本地音效
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] );
}
}
this.ctx = this.canvas.nativeElement.getContext('2d');
this.canvas.nativeElement.width = this.canvasWidth;
this.canvas.nativeElement.height = this.canvasHeight;
window['curCtx'] = this.ctx;
window['curImages'] = this.images;
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) {
if (item) {
......@@ -174,50 +1062,39 @@ export class PlayComponent implements OnInit, OnDestroy {
}
}
initListener() {
this.winResizeEventStream
.pipe(debounceTime(500))
.subscribe(data => {
const element = this.canvas.nativeElement;
this.g_winResizeEventStream.pipe(debounceTime(500)).subscribe(data => {
this.renderAfterResize();
});
// ---------------------------------------------
const setParentOffset = () => {
const rect = this.canvas.nativeElement.getBoundingClientRect();
this.canvasLeft = rect.left;
this.canvasTop = rect.top;
const addTouchListener = () => {
element.addEventListener('touchstart', touchDownFunc);
element.addEventListener('touchmove', touchMoveFunc);
element.addEventListener('touchend', touchUpFunc);
element.addEventListener('touchcancel', touchUpFunc);
};
const setMxMyByTouch = (event) => {
if (event.touches.length <= 0) {
return;
}
if (this.canvasLeft == null) {
setParentOffset();
}
this.mx = event.touches[0].pageX - this.canvasLeft;
this.my = event.touches[0].pageY - this.canvasTop;
const removeTouchListener = () => {
element.removeEventListener('touchstart', touchDownFunc);
element.removeEventListener('touchmove', touchMoveFunc);
element.removeEventListener('touchend', touchUpFunc);
element.removeEventListener('touchcancel', touchUpFunc);
};
const setMxMyByMouse = (event) => {
this.mx = event.offsetX;
this.my = event.offsetY;
const addMouseListener = () => {
element.addEventListener('mousedown', mouseDownFunc);
element.addEventListener('mousemove', mouseMoveFunc);
element.addEventListener('mouseup', mouseUpFunc);
};
const removeMouseListener = () => {
element.removeEventListener('mousedown', mouseDownFunc);
element.removeEventListener('mousemove', mouseMoveFunc);
element.removeEventListener('mouseup', mouseUpFunc);
};
// ---------------------------------------------
let firstTouch = true;
const touchDownFunc = (e) => {
if (firstTouch) {
firstTouch = false;
if (this.g_firstTouch) {
this.g_firstTouch = false;
removeMouseListener();
}
setMxMyByTouch(e);
......@@ -233,8 +1110,8 @@ export class PlayComponent implements OnInit, OnDestroy {
};
const mouseDownFunc = (e) => {
if (firstTouch) {
firstTouch = false;
if (this.g_firstTouch) {
this.g_firstTouch = false;
removeTouchListener();
}
setMxMyByMouse(e);
......@@ -249,135 +1126,85 @@ export class PlayComponent implements OnInit, OnDestroy {
this.mapUp(e);
};
const element = this.canvas.nativeElement;
const addTouchListener = () => {
element.addEventListener('touchstart', touchDownFunc);
element.addEventListener('touchmove', touchMoveFunc);
element.addEventListener('touchend', touchUpFunc);
element.addEventListener('touchcancel', touchUpFunc);
};
const removeTouchListener = () => {
element.removeEventListener('touchstart', touchDownFunc);
element.removeEventListener('touchmove', touchMoveFunc);
element.removeEventListener('touchend', touchUpFunc);
element.removeEventListener('touchcancel', touchUpFunc);
const setMxMyByTouch = event => {
if (event.touches.length <= 0) {
return;
}
if (this.g_canvasLeft == null) {
setParentOffset();
}
this.g_clickX = event.touches[0].pageX - this.g_canvasLeft;
this.g_clickY = event.touches[0].pageY - this.g_canvasTop;
};
const addMouseListener = () => {
element.addEventListener('mousedown', mouseDownFunc);
element.addEventListener('mousemove', mouseMoveFunc);
element.addEventListener('mouseup', mouseUpFunc);
const setParentOffset = () => {
const rect = this.canvas.nativeElement.getBoundingClientRect();
this.g_canvasLeft = rect.left;
this.g_canvasTop = rect.top;
};
const removeMouseListener = () => {
element.removeEventListener('mousedown', mouseDownFunc);
element.removeEventListener('mousemove', mouseMoveFunc);
element.removeEventListener('mouseup', mouseUpFunc);
const setMxMyByMouse = (event) => {
this.g_clickX = event.offsetX;
this.g_clickY = event.offsetY;
};
addMouseListener();
addTouchListener();
}
playAudio(key, now = false, callback = null) {
const audio = this.audioObj[key];
if (audio) {
if (now) {
audio.pause();
audio.currentTime = 0;
showArr(arr) {
if (!arr) {
return;
}
for (let i = 0; i < arr.length; i++) {
arr[i].visible = true;
}
}
if (callback) {
audio.onended = () => {
callback();
};
hideArr(arr) {
if (!arr) {
return;
}
audio.play();
for (let i = 0; i < arr.length; i++) {
arr[i].visible = false;
}
}
loadResources() {
const pr = [];
this.rawImages.forEach((value, key) => {// 预加载图片
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);
IsPC() {
if (window["ELECTRON"]) {
return false; // 封装客户端标记
}
preload(url) {
return new Promise((resolve, reject) => {
const img = new Image();
// img.crossOrigin = "anonymous";
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
if (
document.body.ontouchmove !== undefined &&
document.body.ontouchmove !== undefined
) {
return false;
} else {
return true;
}
preloadAudio(url) {
return new Promise((resolve, reject) => {
const audio = new Audio();
audio.oncanplay = (a) => {
resolve();
};
audio.onerror = () => {
reject();
};
audio.src = url;
audio.load();
});
}
renderAfterResize() {
this.canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight;
this.init();
this.g_canvasWidth = this.wrap.nativeElement.clientWidth;
this.g_canvasHeight = this.wrap.nativeElement.clientHeight;
this.update();
this.handleScreenResize()
}
checkClickTarget(target) {
if (!target) {
return false;
}
const rect = target.getBoundingBox();
if (this.checkPointInRect(this.mx, this.my, rect)) {
if (this.checkPointInRect(this.g_clickX, this.g_clickY, rect)) {
return true;
}
return false;
}
getWorlRect(target) {
let rect = target.getBoundingBox();
if (target.parent) {
const pRect = this.getWorlRect(target.parent);
rect.x += pRect.x;
rect.y += pRect.y;
......@@ -394,297 +1221,772 @@ export class PlayComponent implements OnInit, OnDestroy {
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 };
}
addUrlToAudioObj(key, url = null, vlomue = 1, loop = false, callback = null) {
const audioObj = this.audioObj;
if (url == null) {
url = key;
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;
}
this.rawAudios.set(key, url);
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)
})
}
const audio = new Audio();
audio.src = url;
audio.load();
audio.loop = loop;
audio.volume = vlomue;
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)
})
}
audioObj[key] = audio;
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)
})
}
if (callback) {
audio.onended = () => {
callback();
subscribeMapDragEvent(id, trigger, move, release){
this.subscribeMapDownEvent(id,()=>{})
this.m_mapDragObject[id] = {
trigger,
move,
release
};
}
}
addUrlToImages(url) {
this.rawImages.set(url, url);
releaseDragElement(){
if(this.g_currentDragElementID){
this.m_mapDragObject[this.g_currentDragElementID].release()
}
}
// 全局初始化入口,当资源加载完毕后执行
initSystem() {
this.g_canvasWidth = this.wrap.nativeElement.clientWidth;
this.g_canvasHeight = this.wrap.nativeElement.clientHeight;
const sx = this.g_canvasWidth / this.g_canvasBaseW;
const sy = this.g_canvasHeight / this.g_canvasBaseH;
const s = Math.min(sx, sy);
this.g_mapScale = s;
this.g_cartoon.mapScale = this.g_mapScale;
this.g_cartoon.clientWidth = this.wrap.nativeElement.clientWidth;
this.g_cartoon.clientHeight = this.wrap.nativeElement.clientHeight;
this.m_renderArr = [];
this.m_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)
})
}
/**
* 添加默认数据 便于无数据时的展示
*/
initDefaultData() {
sendServerEvent(key, data) {
const c = (<any> window).courseware;
c.sendEvent(key, JSON.stringify(data));
}
if (!this.data.pic_url) {
this.data.pic_url = 'assets/play/default/pic.jpg';
this.data.pic_url_2 = 'assets/play/default/pic.jpg';
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);
}
/**
* 添加预加载图片
*/
initImg() {
stopAllTimeout(){
this.m_setTimeoutIDs.forEach(id=>clearTimeout(id))
this.m_setTimeoutIDs = []
}
this.addUrlToImages(this.data.pic_url);
this.addUrlToImages(this.data.pic_url_2);
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)
}
}
/**
* 添加预加载音频
*/
initAudio() {
setRenderZIndex(element, zIndex){
let index = null;
for(let i=0; i<this.m_renderObject.length; i++){
if( this.m_renderObject[i].element.id == element.id ){
index = i
}
}
if(index){
this.m_renderObject.splice(index, 1)
this.m_renderObject.push({element:element, zIndex:zIndex?zIndex:1})
this.m_renderObject.sort((a,b)=>{
return a.zIndex - b.zIndex
})
// 音频资源
this.addUrlToAudioObj(this.data.audio_url);
this.addUrlToAudioObj(this.data.audio_url_2);
this.m_renderArr = []
this.m_renderObject.forEach(item=>{
this.m_renderArr.push(item.element)
})
}
}
// 音效
this.addUrlToAudioObj('click', this.rawAudios.get('click'), 0.3);
deleteElementInRender(id){
let index = null;
for(let i=0; i<this.m_renderObject.length; i++){
if( this.m_renderObject[i].element.id == id ){
index = i
}
}
if(index){
this.m_renderObject.splice(index, 1)
this.m_renderObject.sort((a,b)=>{
return a.zIndex - b.zIndex
})
this.m_renderArr = []
this.m_renderObject.forEach(item=>{
this.m_renderArr.push(item.element)
})
}else{
console.warn("Can not found element id:" + id)
}
}
enableMoveAsstant(callback){
if (this.m_moveAsstantIntervalId) {
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 = []
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();
}
getMaxSubstringLength(str){
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
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)
});
return totlaWidth
}
alignLeft(elementArray, spacing, startX = 0, withAni?, callback?){
let laseX = startX;
elementArray.forEach((element, index) => {
let bd = element.ref.getBoundingBox()
if(withAni){
tweenChange(element.ref, {x: laseX + bd.width / 2}, 0.2, ()=>{
this.g_cartoon.saveSize(element.id)
if(length == (index+1)){
callback && callback()
}
})
}else{
element.ref.x = laseX + bd.width / 2
this.g_cartoon.saveSize(element.id)
if(length == (index+1)){
callback && callback()
}
}
laseX = (laseX + bd.width + spacing)
});
}
/**
* 初始化数据
*/
initData() {
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)
}
const sx = this.canvasWidth / this.canvasBaseW;
const sy = this.canvasHeight / this.canvasBaseH;
const s = Math.min(sx, sy);
this.mapScale = s;
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
}
// this.mapScale = sx;
// this.mapScale = sy;
this.renderArr = [];
}
/**
* 初始化试图
*/
initView() {
this.initPic();
this.initBottomPart();
}
initBottomPart() {
const btnLeft = new MySprite();
btnLeft.init(this.images.get('btn_left'));
btnLeft.x = this.canvasWidth - 150 * this.mapScale;
btnLeft.y = this.canvasHeight - 100 * this.mapScale;
btnLeft.setScaleXY(this.mapScale);
this.renderArr.push(btnLeft);
this.btnLeft = btnLeft;
const btnRight = new MySprite();
btnRight.init(this.images.get('btn_right'));
btnRight.x = this.canvasWidth - 50 * this.mapScale;
btnRight.y = this.canvasHeight - 100 * this.mapScale;
btnRight.setScaleXY(this.mapScale);
this.renderArr.push(btnRight);
this.btnRight = btnRight;
}
initPic() {
const maxW = this.canvasWidth * 0.7;
const pic1 = new MySprite();
pic1.init(this.images.get(this.data.pic_url));
pic1.x = this.canvasWidth / 2;
pic1.y = this.canvasHeight / 2;
pic1.setScaleXY(maxW / pic1.width);
this.renderArr.push(pic1);
this.pic1 = pic1;
const label1 = new Label();
label1.text = this.data.text;
label1.textAlign = 'center';
label1.fontSize = 50;
label1.fontName = 'BRLNSDB';
label1.fontColor = '#ffffff';
pic1.addChild(label1);
const pic2 = new MySprite();
pic2.init(this.images.get(this.data.pic_url_2));
pic2.x = this.canvasWidth / 2 + this.canvasWidth;
pic2.y = this.canvasHeight / 2;
pic2.setScaleXY(maxW / pic2.width);
this.renderArr.push(pic2);
this.pic2 = pic2;
this.curPic = pic1;
}
btnLeftClicked() {
// --------------------------------------------------
// -------------- Template function ---------------
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
//
// .-~~~~~~~~~-._ _.-~~~~~~~~~-.
// __.' ~. .~ `.__
// .'// \./ \\`.
// .'// | \\`.
// .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`.
// .'//.-" `-. | .-' "-.\\`.
// .'//______.============-.. \ | / ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
// --------------------------------------------------
// showParticle( element_id ) 泡泡效果
// --------------------------------------------------
// showEndPatal() / stopEndPatal() 花瓣飘落结束动画
// --------------------------------------------------
// showCorrectPatal() 指定元素上面飘花
// --------------------------------------------------
// convertPercentToRadian() 将百分比转换为弧长 第一个参数是百分比,第二个参数是方向 true为逆时针,false为顺时针。用于ShapeCircle换圆弧
// --------------------------------------------------
// movePaoWuxian() 元素抛物线跳
// --------------------------------------------------
// showJellyAnimation()------------------------------
// showBlingStar()----------------------显示星星效果--
// --------------------------------------------------
this.lastPage();
}
btnRightClicked() {
this.nextPage();
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)
}
lastPage() {
if (this.curPic == this.pic1) {
return;
}
this.canTouch = false;
const moveLen = this.canvasWidth;
tweenChange(this.pic1, {x: this.pic1.x + moveLen}, 1);
tweenChange(this.pic2, {x: this.pic2.x + moveLen}, 1, () => {
this.canTouch = true;
this.curPic = this.pic1;
});
// 泡泡
showParticle(card) {
let myCard = this.g_cartoon.getCartoonElementRelativePosition(card.id)
showPopParticle(this.g_cartoon.images.get("_bubble"), { x: myCard.x , y: myCard.y }, this.g_stage);
}
nextPage() {
if (this.curPic == this.pic2) {
return;
// 选择正确动画
showCorrectPatal(card_id, showTime, callback?) {
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = true;
this.addCorrectPetal(card_id);
setTimeout(()=>{
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = false;
callback && callback()
},showTime)
}
this.canTouch = false;
const moveLen = this.canvasWidth;
tweenChange(this.pic1, {x: this.pic1.x - moveLen}, 1);
tweenChange(this.pic2, {x: this.pic2.x - moveLen}, 1, () => {
this.canTouch = true;
this.curPic = this.pic2;
});
stopAllCorrectPatal(){
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = false;
}
pic1Clicked() {
this.playAudio(this.data.audio_url);
addCorrectPetal(card_id) {
if (!this.m_showElementPetalFlag) {
return;
}
pic2Clicked() {
this.playAudio(this.data.audio_url_2);
}
let element = this.g_cartoon.getCartoonElement(card_id)
const petal = new MySprite(this.g_ctx);
const id = Math.ceil(Math.random() * 3);
petal.init(this.g_cartoon.images.get(this.m_PetalImage + id));
const randomS = (Math.random() * 0.4 + 0.6) * this.g_mapScale * 0.5;
petal.setScaleXY(randomS);
const randomR = Math.random() * 360;
petal.rotation = randomR;
const randomX = Math.random() * element.ref.width * this.g_mapScale;
mapDown(event) {
petal.x = element.ref.x - (element.ref.width * this.g_mapScale / 2) + randomX;
petal.y = element.ref.y - (element.ref.height * this.g_mapScale / 2);
if (!this.canTouch) {
return;
const randomT = 1 + Math.random() * 2;
petal["time"] = randomT;
let randomTR = 360 * Math.random(); // - 180;
if (Math.random() < 0.5) {
randomTR *= -1;
}
petal["tr"] = randomTR;
if ( this.checkClickTarget(this.btnLeft) ) {
this.btnLeftClicked();
return;
this.m_elementPetalArr.push(petal);
moveItem(
petal,
petal.x,
element.ref.y + (element.ref.height * this.g_mapScale / 2),
petal["time"],
() => {
removeItemFromArr(this.m_elementPetalArr, petal);
}
);
rotateItem(petal, petal["tr"], petal["time"]);
setTimeout(() => {
this.addCorrectPetal(card_id);
}, 200);
}
if ( this.checkClickTarget(this.btnRight) ) {
this.btnRightClicked();
return;
// 结束动画花瓣飘落
showEndPatal() {
this.m_endPageArr = [];
this.m_showPetalFlag = true;
this.addPetal();
}
if ( this.checkClickTarget(this.pic1) ) {
this.pic1Clicked();
return;
stopEndPatal() {
this.m_endPageArr = [];
this.m_showPetalFlag = false;
}
if ( this.checkClickTarget(this.pic2) ) {
this.pic2Clicked();
addPetal() {
if (!this.m_showPetalFlag) {
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);
}
mapMove(event) {
);
rotateItem(petal, petal["tr"], petal["time"]);
setTimeout(() => {
this.addPetal();
}, 100);
}
mapUp(event) {
}
getPetal() {
const petal = new MySprite(this.g_ctx);
const id = Math.ceil(Math.random() * 3);
petal.init(this.g_cartoon.images.get(this.m_PetalImage + id));
const randomS = (Math.random() * 0.4 + 0.6) * this.g_mapScale;
petal.setScaleXY(randomS);
update() {
const randomR = Math.random() * 360;
petal.rotation = randomR;
// ----------------------------------------------------------
this.animationId = window.requestAnimationFrame(this.update.bind(this));
// 清除画布内容
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
// tween 更新动画
TWEEN.update();
// ----------------------------------------------------------
const randomX = Math.random() * this.g_canvasWidth;
petal.x = randomX;
petal.y = (-petal.height / 2) * petal.scaleY;
const randomT = 2 + Math.random() * 5;
petal["time"] = randomT;
let randomTR = 360 * Math.random(); // - 180;
if (Math.random() < 0.5) {
randomTR *= -1;
}
petal["tr"] = randomTR;
this.updateArr(this.renderArr);
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()
})
})
})
}
showShakeAnimation(element_id, callback?){
let element = this.g_cartoon.getCartoonElement(element_id).ref
let originX = element.x
tweenChange(element,{ x: originX - 10*this.g_mapScale }, 0.1, ()=>{
tweenChange(element,{ x: originX + 10*this.g_mapScale }, 0.1, ()=>{
tweenChange(element,{ x: originX }, 0.1, ()=>{
callback && callback()
})
})
})
}
convertPercentToRadian(per, direction){
let radian = 0;
if(direction) { //逆时针
if(per*360 > 270){
radian = 361 - (per*360 - 270)
}else{
radian = 270 - per*360
}
}else{ //顺时针
if(per*360 > 90){
radian = per*360 - 90
}else{
radian = 270 + per*360
}
}
return (radian * Math.PI) / 180;
}
showBlingStar(element, callback?){
let rect = element.getBoundingBox()
showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 0.5);
this.m_setTimeoutIDs.push(setTimeout(() => {
callback && callback()
}, 2000))
// setTimeout(()=>{
// showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 1.8);
// },200)
// setTimeout(()=>{
// showBlingBling(this.g_cartoon.images.get('icon_star'), rect, element, 0.5, 1, 0.08, 1.6);
// },400)
}
movePaoWuxian(element,dis,time,callback?){
let disX = dis.x - element.x
let disY = (element.y - dis.y)
let count = 0
let runTime = time/5
let vx = disX/runTime
let a = -0.05
let vy0 = disY/runTime - 0.5*a*runTime
let id = setInterval(()=>{
element.x += vx
element.y -= vy0 + a*count
count++;
if(count>runTime){
clearInterval(id)
callback && callback()
}
}, 5);
}
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', "assets/play/bg.jpg"],
['btn_left', "assets/play/btn_left.png"],
['btn_right', "assets/play/btn_right.png"],
// ['text_bg', "assets/play/text_bg.png"],
'bg_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',
};
];
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 resAudio = [
const multiSizeBackground = {
['click', "assets/play/music/click.mp3"],
}
];
export {res, resAudio};
export { localImages, localAudios, multiSizeBackground };
\ No newline at end of file
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 */
@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