Commit 8c4ec4f8 authored by limingzhe's avatar limingzhe

update

parent 4b326c83
...@@ -18,66 +18,66 @@ ...@@ -18,66 +18,66 @@
font-family: 'BRLNSDB'; font-family: 'BRLNSDB';
src: url("../../../assets/font/BRLNSDB.TTF") ; src: url("../../../assets/font/BRLNSDB.TTF") ;
} }
//
@font-face //@font-face
{ //{
font-family: 'BRLNSB'; // font-family: 'BRLNSB';
src: url("../../../assets/font/BRLNSB.TTF") ; // src: url("../../../assets/font/BRLNSB.TTF") ;
} //}
//
@font-face //@font-face
{ //{
font-family: 'BRLNSR'; // font-family: 'BRLNSR';
src: url("../../../assets/font/BRLNSR.TTF") ; // src: url("../../../assets/font/BRLNSR.TTF") ;
} //}
//
@font-face //@font-face
{ //{
font-family: 'GOTHIC'; // font-family: 'GOTHIC';
src: url("../../../assets/font/GOTHIC.TTF") ; // src: url("../../../assets/font/GOTHIC.TTF") ;
} //}
//
@font-face //@font-face
{ //{
font-family: 'GOTHICB'; // font-family: 'GOTHICB';
src: url("../../../assets/font/GOTHICB.TTF") ; // src: url("../../../assets/font/GOTHICB.TTF") ;
} //}
//
@font-face //@font-face
{ //{
font-family: 'GOTHICBI'; // font-family: 'GOTHICBI';
src: url("../../../assets/font/GOTHICBI.TTF") ; // src: url("../../../assets/font/GOTHICBI.TTF") ;
} //}
//
@font-face //@font-face
{ //{
font-family: 'GOTHICI'; // font-family: 'GOTHICI';
src: url("../../../assets/font/GOTHICI.TTF") ; // src: url("../../../assets/font/GOTHICI.TTF") ;
} //}
//
@font-face //@font-face
{ //{
font-family: 'MMTextBook'; // font-family: 'MMTextBook';
src: url("../../../assets/font/MMTextBook.otf") ; // src: url("../../../assets/font/MMTextBook.otf") ;
} //}
//
@font-face //@font-face
{ //{
font-family: 'MMTextBook-Bold'; // font-family: 'MMTextBook-Bold';
src: url("../../../assets/font/MMTextBook-Bold.otf") ; // src: url("../../../assets/font/MMTextBook-Bold.otf") ;
} //}
//
@font-face //@font-face
{ //{
font-family: 'MMTextBook-BoldItalic'; // font-family: 'MMTextBook-BoldItalic';
src: url("../../../assets/font/MMTextBook-BoldItalic.otf") ; // src: url("../../../assets/font/MMTextBook-BoldItalic.otf") ;
} //}
//
@font-face //@font-face
{ //{
font-family: 'MMTextBook-Italic'; // font-family: 'MMTextBook-Italic';
src: url("../../../assets/font/MMTextBook-Italic.otf") ; // src: url("../../../assets/font/MMTextBook-Italic.otf") ;
} //}
@mixin tool-btn { @mixin tool-btn {
border: 1px solid #ddd; border: 1px solid #ddd;
display: flex; display: flex;
......
@import '../style/common_mixin.css';
.model-content {
width: 100%;
height: 100%;
}
<div class="model-content"> <div class="model-content">
<div class="card-config">
<div *ngFor="let item of dataArray; let i = index" class="card-item" style="padding: 0.5vw;" >
<div style="position: absolute; left: 200px; top: 100px; width: 800px;"> <div class="card-item-content border">
<div class="card-item-content">
<input type="text" nz-input [(ngModel)]="item.text" (blur)="save()"> <div class="title" >
第-<strong>{{ i + 1 }}</strong>-题
<app-upload-image-with-preview
[picUrl]="item.pic_url"
(imageUploaded)="onImageUploadSuccess($event, 'pic_url')"
></app-upload-image-with-preview>
<app-audio-recorder
[audioUrl]="item.audio_url"
(audioUploaded)="onAudioUploadSuccess($event, 'audio_url')"
></app-audio-recorder>
<app-custom-hot-zone></app-custom-hot-zone>
<app-upload-video></app-upload-video>
<app-lesson-title-config></app-lesson-title-config>
</div> </div>
<div class="section" >
<div class="section-title" >
问题
</div>
<div class="section-content">
<div style="flex:1">
<div style="display: flex; margin-bottom: 10px;">
<div style="flex:1">
文字
</div>
<div style="flex:5">
<input type="text" nz-input placeholder="" [(ngModel)]="item.question.text" (blur)="saveItem()" style="width: 250px;" />
</div>
</div>
<div style="display: flex; margin-bottom: 10px;">
<div style="flex:1">
音频
</div>
<div style="flex:5">
<app-audio-recorder [audioUrl]="item.question.audio_url" (audioUploaded)="onAudioUploadSuccessByItem($event, item.question)" ></app-audio-recorder>
</div>
</div>
<!-- div style="position: absolute; left: 1000px; top: 100px; width: 300px;"> <div style="display: flex; margin-bottom: 10px;">
<div style="flex:1">
<input type="text" nz-input [(ngModel)]="item.text_2" (blur)="save()"> 时间
</div>
<app-upload-image-with-preview <div style="flex:5">
[picUrl]="item.pic_url_2" <input type="text" nz-input placeholder="" [(ngModel)]="item.time" (blur)="saveItem()" style="width: 80px;" /><span style="margin-left: 10px;"></span>
(imageUploaded)="onImageUploadSuccess($event, 'pic_url_2')" </div>
></app-upload-image-with-preview> </div>
</div>
<app-audio-recorder
[audioUrl]="item.audio_url_2"
(audioUploaded)="onAudioUploadSuccess($event, 'audio_url_2')"
></app-audio-recorder>
</div -->
</div>
<!--<app-audio-recorder-->
<!--[audioUrl]="item.audio_url"-->
<!--(audioUploaded)="onAudioUploadSuccess($event)"-->
<!--&gt;</app-audio-recorder>-->
<!--<div *ngFor="let it of picArr; let i = index"-->
<!--nz-col nzSpan="8" >-->
<!--<div class="item-box">-->
<!--<app-upload-image-with-preview-->
<!--style="width: 100%"-->
<!--[picUrl]="it.pic_url"-->
<!--(imageUploaded)="onImageUploadSuccessByItem($event, it)"-->
<!--&gt;</app-upload-image-with-preview>-->
<!--<div style="display: flex; justify-items: center; padding-top: 10px">-->
<!--<app-audio-recorder-->
<!--[audioUrl]="it.audio_url"-->
<!--(audioUploaded)="onAudioUploadSuccessByItem($event, it)">-->
<!--</app-audio-recorder>-->
<!--<button style="margin-left: 10px;" nz-button nzType="danger" (click)="deleteItem(it)">-->
<!--<i nz-icon type="close"></i>-->
<!--</button>-->
<!--</div>-->
<!--</div>-->
<!--&lt;!&ndash;<h5> id-{{i+1}} </h5>&ndash;&gt;-->
<!--&lt;!&ndash;<div style="display: flex; align-items: center; justify-content: center; padding-bottom: 5px">&ndash;&gt;-->
<!--&lt;!&ndash;<input type="text" nz-input placeholder="" [(ngModel)]="it.text" (blur)="saveItem()">&ndash;&gt;-->
<!--&lt;!&ndash;<button style="margin-left: 10px;" nz-button nzType="danger" (click)="deleteItem(it)">&ndash;&gt;-->
<!--&lt;!&ndash;<i nz-icon type="close"></i>&ndash;&gt;-->
<!--&lt;!&ndash;</button>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;<app-upload-image-with-preview&ndash;&gt;-->
<!--&lt;!&ndash;style="width: 100%"&ndash;&gt;-->
<!--&lt;!&ndash;[picUrl]="it.pic_url"&ndash;&gt;-->
<!--&lt;!&ndash;(imageUploaded)="onImageUploadSuccessByItem($event, it)"&ndash;&gt;-->
<!--&lt;!&ndash;&gt;</app-upload-image-with-preview>&ndash;&gt;-->
<!--&lt;!&ndash;<div style="display: flex; align-items: center; justify-content: center">&ndash;&gt;-->
<!--&lt;!&ndash;<span style="width: 80px;">&ndash;&gt;-->
<!--&lt;!&ndash;question:&ndash;&gt;-->
<!--&lt;!&ndash;</span>&ndash;&gt;-->
<!--&lt;!&ndash;<app-audio-recorder&ndash;&gt;-->
<!--&lt;!&ndash;[audioUrl]="it['q_audio_url']"&ndash;&gt;-->
<!--&lt;!&ndash;(audioUploaded)="onAudioUploadSuccessByItem($event, it, 'q')">&ndash;&gt;-->
<!--&lt;!&ndash;</app-audio-recorder>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;<div style="display: flex; align-items: center; justify-content: center">&ndash;&gt;-->
<!--&lt;!&ndash;<span style="width: 80px;">&ndash;&gt;-->
<!--&lt;!&ndash;answer:&ndash;&gt;-->
<!--&lt;!&ndash;</span>&ndash;&gt;-->
<!--&lt;!&ndash;<app-audio-recorder&ndash;&gt;-->
<!--&lt;!&ndash;[audioUrl]="it['a_audio_url']"&ndash;&gt;-->
<!--&lt;!&ndash;(audioUploaded)="onAudioUploadSuccessByItem($event, it, 'a')">&ndash;&gt;-->
<!--&lt;!&ndash;</app-audio-recorder>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;<nz-radio-group [(ngModel)]="it.radioValue" >&ndash;&gt;-->
<!--&lt;!&ndash;<label nz-radio nzValue="A" (click)="radioClick(it, 'A')"> <i nz-icon nzType="check" nzTheme="outline"></i> </label>&ndash;&gt;-->
<!--&lt;!&ndash;<label nz-radio nzValue="B" (click)="radioClick(it, 'B')"> <i nz-icon nzType="close" nzTheme="outline"></i> </label>&ndash;&gt;-->
<!--&lt;!&ndash;</nz-radio-group>&ndash;&gt;-->
<!--</div>-->
<!--<div nz-col nzSpan="8" class="add-btn-box" >-->
<!--&lt;!&ndash;<div style="width: 100%; height: 100%;">&ndash;&gt;-->
<!--<button style=" margin: auto; width: 60%; height: 60%;" nz-button nzType="dashed" class="add-btn"-->
<!--(click)="addPic()">-->
<!--<i nz-icon nzType="plus-circle" nzTheme="outline"></i>-->
<!--Add-->
<!--</button>-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--</div>-->
<!--&lt;!&ndash;<div style="padding-bottom: 30px;">&ndash;&gt;-->
<!--&lt;!&ndash;<h5> title-sound: </h5>&ndash;&gt;-->
<!--&lt;!&ndash;<app-audio-recorder&ndash;&gt;-->
<!--&lt;!&ndash;[audioUrl]="item.contentObj.title_audio_url"&ndash;&gt;-->
<!--&lt;!&ndash;(audioUploaded)="onAudioUploadSuccessByItem($event, item.contentObj, 'title')">&ndash;&gt;-->
<!--&lt;!&ndash;</app-audio-recorder>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;<div style="padding-bottom: 30px;">&ndash;&gt;-->
<!--&lt;!&ndash;<h5> bg-sound: </h5>&ndash;&gt;-->
<!--&lt;!&ndash;<app-audio-recorder&ndash;&gt;-->
<!--&lt;!&ndash;[audioUrl]="item.contentObj.bg_audio_url"&ndash;&gt;-->
<!--&lt;!&ndash;(audioUploaded)="onAudioUploadSuccessByItem($event, item.contentObj, 'bg')">&ndash;&gt;-->
<!--&lt;!&ndash;</app-audio-recorder>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;<span style="margin-bottom: 20px"> 10 : 23 </span>&ndash;&gt;-->
<!--&lt;!&ndash;<div *ngFor="let it of picArr; let i = index">&ndash;&gt;-->
<!--&lt;!&ndash;<span> pic-{{i + 1}}: </span>&ndash;&gt;-->
<!--&lt;!&ndash;<div style="display: flex; align-items: center; padding-bottom: 20px">&ndash;&gt;-->
<!--&lt;!&ndash;<div style="width: 40%; padding-right: 20px">&ndash;&gt;-->
<!--&lt;!&ndash;<app-upload-image-with-preview&ndash;&gt;-->
<!--&lt;!&ndash;[picUrl]="it.pic_url"&ndash;&gt;-->
<!--&lt;!&ndash;(imageUploaded)="onImageUploadSuccessByItem($event, it)"&ndash;&gt;-->
<!--&lt;!&ndash;&gt;</app-upload-image-with-preview>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;<div class="pic-sound-box">&ndash;&gt;-->
<!--&lt;!&ndash;<div nz-row style="width: 50%; padding-bottom: 20px;">&ndash;&gt;-->
<!--&lt;!&ndash;<div *ngFor="let it2 of it.soundArr; let i2 = index" nz-col nzSpan="8">&ndash;&gt;-->
<!--&lt;!&ndash;<label nz-checkbox nzValue="{{'answer_' + (i2 + 1)}}" [(ngModel)]="it2.answer" (ngModelChange)="clickCheckBox()" >{{i2 + 1}}</label>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;<div *ngFor="let it2 of it.soundArr; let i2 = index" style="display: flex; align-items: center; padding-bottom: 5px">&ndash;&gt;-->
<!--&lt;!&ndash;<span style="padding-right: 10px">sound-{{i2 + 1}}:</span>&ndash;&gt;-->
<!--&lt;!&ndash;<app-audio-recorder&ndash;&gt;-->
<!--&lt;!&ndash;[audioUrl]="it2.audio_url"&ndash;&gt;-->
<!--&lt;!&ndash;(audioUploaded)="onAudioUploadSuccessByItem($event, it2)">&ndash;&gt;-->
<!--&lt;!&ndash;</app-audio-recorder>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;<div style="margin: auto; width: 95%;" nz-row nzType="flex" nzJustify="start" nzAlign="middle">&ndash;&gt;-->
<!--&lt;!&ndash;<div *ngFor="let it of picArr; let i = index"&ndash;&gt;-->
<!--&lt;!&ndash;nz-col nzSpan="8" >&ndash;&gt;-->
<!--&lt;!&ndash;<div class="item-box">&ndash;&gt;-->
<!--&lt;!&ndash;<h5> id-{{i+1}} </h5>&ndash;&gt;-->
<!--&lt;!&ndash;<div style="display: flex; align-items: center; justify-content: center; padding-bottom: 5px">&ndash;&gt;-->
<!--&lt;!&ndash;<input type="text" nz-input placeholder="" [(ngModel)]="it.text" (blur)="saveItem()">&ndash;&gt;-->
<!--&lt;!&ndash;<button style="margin-left: 10px;" nz-button nzType="danger" (click)="deleteItem(it)">&ndash;&gt;-->
<!--&lt;!&ndash;<i nz-icon type="close"></i>&ndash;&gt;-->
<!--&lt;!&ndash;</button>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;<app-upload-image-with-preview&ndash;&gt;-->
<!--&lt;!&ndash;style="width: 100%"&ndash;&gt;-->
<!--&lt;!&ndash;[picUrl]="it.pic_url"&ndash;&gt;-->
<!--&lt;!&ndash;(imageUploaded)="onImageUploadSuccessByItem($event, it)"&ndash;&gt;-->
<!--&lt;!&ndash;&gt;</app-upload-image-with-preview>&ndash;&gt;-->
<!--&lt;!&ndash;<div style="display: flex; align-items: center; justify-content: center">&ndash;&gt;-->
<!--&lt;!&ndash;<span style="width: 80px;">&ndash;&gt;-->
<!--&lt;!&ndash;question:&ndash;&gt;-->
<!--&lt;!&ndash;</span>&ndash;&gt;-->
<!--&lt;!&ndash;<app-audio-recorder&ndash;&gt;-->
<!--&lt;!&ndash;[audioUrl]="it['q_audio_url']"&ndash;&gt;-->
<!--&lt;!&ndash;(audioUploaded)="onAudioUploadSuccessByItem($event, it, 'q')">&ndash;&gt;-->
<!--&lt;!&ndash;</app-audio-recorder>&ndash;&gt;-->
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<!--&lt;!&ndash;<div style="display: flex; align-items: center; justify-content: center">&ndash;&gt;-->
<!--&lt;!&ndash;<span style="width: 80px;">&ndash;&gt;--> <div style="flex:1">
<!--&lt;!&ndash;answer:&ndash;&gt;--> <div style="display: flex; ">
<!--&lt;!&ndash;</span>&ndash;&gt;--> <div style="flex:1">
<!--&lt;!&ndash;<app-audio-recorder&ndash;&gt;--> 图片
<!--&lt;!&ndash;[audioUrl]="it['a_audio_url']"&ndash;&gt;--> </div>
<!--&lt;!&ndash;(audioUploaded)="onAudioUploadSuccessByItem($event, it, 'a')">&ndash;&gt;--> <div style="flex:5">
<!--&lt;!&ndash;</app-audio-recorder>&ndash;&gt;--> <app-upload-image-with-preview style="width: 100%;" [picUrl]="item.question.image_url" (imageUploaded)="onImageUploadSuccessByItem($event, item.question)"></app-upload-image-with-preview>
</div>
</div>
</div>
</div>
</div>
<!--&lt;!&ndash;</div>&ndash;&gt;-->
<div class="section" >
<div class="section-title" >
正确选项
</div>
<div class="section-content">
<div style="flex:10">
<div style="display: flex; margin-bottom: 10px;">
<div style="flex:1">
文字
</div>
<div style="flex:5">
<input type="text" nz-input placeholder="" [(ngModel)]="item.choice.correct.text" (blur)="saveItem()" />
</div>
</div>
<div style="display: flex; margin-bottom: 10px;">
<div style="flex:1">
图片
</div>
<div style="flex:5">
<app-upload-image-with-preview style="width: 100%;" [picUrl]="item.choice.correct.image_url" (imageUploaded)="onImageUploadSuccessByItem($event, item.choice.correct)"></app-upload-image-with-preview>
</div>
</div>
<!--&lt;!&ndash;<nz-radio-group [(ngModel)]="it.radioValue" >&ndash;&gt;--> <div style="display: flex; ">
<!--&lt;!&ndash;<label nz-radio nzValue="A" (click)="radioClick(it, 'A')"> <i nz-icon nzType="check" nzTheme="outline"></i> </label>&ndash;&gt;--> <div style="flex:2">
<!--&lt;!&ndash;<label nz-radio nzValue="B" (click)="radioClick(it, 'B')"> <i nz-icon nzType="close" nzTheme="outline"></i> </label>&ndash;&gt;--> 显示选项
<!--&lt;!&ndash;</nz-radio-group>&ndash;&gt;--> </div>
<div style="flex:4">
<nz-radio-group [(ngModel)]="item.choice.correct.isText" (ngModelChange)="saveItem()" >
<label nz-radio [nzValue]="true">文字</label>
<label nz-radio [nzValue]="false">图片</label>
</nz-radio-group>
</div>
</div>
</div>
<div style="flex:20">
<!--&lt;!&ndash;</div>&ndash;&gt;--> </div>
</div>
</div>
<div class="section" >
<div class="section-title" >
错误选项
<div *ngIf="item.choice.incorrect.length<3" style="text-align: center; float: right;">
<button nz-button nzType="primary" (click)="addChoice(i)" >
<i nz-icon nzType="plus-circle" nzTheme="outline"></i>
添加
</button>
</div>
</div>
<div class="section-content">
<div *ngFor="let choiceItem of item.choice.incorrect; let choiceIndex = index" style="width:220px; height:230px; border:1px solid #CCC; padding:5px; border-radius: 5px; margin: 0 10px;">
<div style="display: flex; margin-bottom: 10px;">
<div style="flex:1">
文字
</div>
<div style="flex:5">
<input type="text" nz-input placeholder="" [(ngModel)]="choiceItem.text" (blur)="saveItem()" />
</div>
</div>
<!--&lt;!&ndash;</div>&ndash;&gt;--> <div style="display: flex; margin-bottom: 10px;">
<div style="flex:1">
图片
</div>
<div style="flex:5">
<app-upload-image-with-preview style="width: 100%;" [picUrl]="choiceItem.image_url" (imageUploaded)="onImageUploadSuccessByItem($event, choiceItem)"></app-upload-image-with-preview>
</div>
</div>
<div style="display: flex; ">
<div style="flex:2">
显示选项
</div>
<div style="flex:4">
<nz-radio-group [(ngModel)]="choiceItem.isText" (ngModelChange)="saveItem()" >
<label nz-radio [nzValue]="true">文字</label>
<label nz-radio [nzValue]="false">图片</label>
</nz-radio-group>
</div>
</div>
<div *ngIf="choiceIndex>0" style="text-align: center;">
<button style="margin-top: 10px;" nz-button nzType="danger" (click)="deleteChoice(i, choiceIndex)" >
<span>删除此选项</span>
</button>
</div>
</div>
</div>
</div>
<div class="section" >
<div style="text-align: right; padding-right: 20px;">
<button style="margin-bottom: 10px;" nz-button nzType="danger" (click)="deleteItem(i)" >
<span>删除本题</span>
</button>
</div>
</div>
</div>
</div>
</div>
<div class="card-item" style="padding: 0.5vw;" >
<button nz-button nzType="primary" class="add-btn" (click)="addItem()">
<i nz-icon nzType="plus-circle" nzTheme="outline"></i>
新建卡片组
</button>
</div>
</div>
<!--</div>--> </div>
@import "../style/common_mixin";
.model-content {
.card-config {
width: 100%;
height: 100%;
margin-left: 10px;
display: flex;
flex-wrap: wrap;
.card-item{
flex:1;
.border {
border-radius: 20px;
border-style: dashed;
padding:20px;
width: 800px;
}
.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;
}
}
}
}
}
import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef} from '@angular/core'; import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef} from '@angular/core';
@Component({ @Component({
selector: 'app-form', selector: 'app-form',
templateUrl: './form.component.html', templateUrl: './form.component.html',
styleUrls: ['./form.component.css'] styleUrls: ['./form.component.scss']
}) })
export class FormComponent implements OnInit, OnChanges, OnDestroy { export class FormComponent implements OnInit, OnChanges, OnDestroy {
// 储存数据用 dataArray = [];
saveKey = "test_0011"; _item: any;
// 储存对象 KEY = 'DataKey_MultipleChoice';
item;
set item(item) {
this._item = item;
}
get item() {
return this._item;
}
@Output()
update = new EventEmitter();
constructor(private appRef: ApplicationRef) { constructor(private appRef: ApplicationRef) {
} }
ngOnInit() { ngOnInit() {
this.item = {}; this.item = {};
this.item.contentObj = {};
// 获取存储的数据 const getData = (<any> window).courseware.getData;
(<any> window).courseware.getData((data) => { getData((data) => {
if (data) { if (data) {
this.item = data; this.item = data;
} else {
this.item = {};
}
if ( !this.item.contentObj ) {
this.item.contentObj = {};
} }
this.init(); this.init();
this.refresh(); this.refresh();
this.saveItem();
}, this.KEY);
}
ngOnChanges() {
}, this.saveKey); }
ngOnDestroy() {
} }
ngOnChanges() { init() {
if (this.item.contentObj.dataArray) {
this.dataArray = this.item.contentObj.dataArray;
} else {
this.dataArray = this.getDefaultPicArr();
this.item.contentObj.dataArray = this.dataArray;
}
} }
ngOnDestroy() { cardItemData(){
return {
time: 3,
question:{
text:"",
image_url:"",
audio_url:""
},
choice:{
correct:{ isText: true, text: "", image_url: "" },
incorrect:[
{ isText: true, text: "", image_url: "" },
{ isText: true, text: "", image_url: "" },
{ isText: true, text: "", image_url: "" },
]
}
};
} }
cardChoiceData(){
return { isText: true, text: "", image_url: "" }
}
getDefaultPicArr() {
let arr = [];
return arr;
}
init() {
initData() {
} }
deleteItem(index) {
if (index !== -1) {
this.dataArray.splice(index, 1);
}
this.save();
}
/** deleteChoice(questionIndex, choiceIndex){
* 储存图片数据 if (questionIndex !== -1 && choiceIndex !== -1) {
* @param e this.dataArray[questionIndex].choice.incorrect.splice(choiceIndex, 1);
*/ }
onImageUploadSuccess(e, key) {
this.item[key] = e.url;
this.save(); this.save();
} }
addChoice(questionIndex) {
let item = this.cardChoiceData();
this.dataArray[questionIndex].choice.incorrect.push(item);
this.saveItem();
}
/** onImageUploadSuccessByItem(e, item) {
* 储存音频数据 item.image_url = e.url
* @param e this.save();
*/ }
onAudioUploadSuccess(e, key) {
this.item[key] = e.url; onAudioUploadSuccessByItem(e, item) {
item.audio_url = e.url;
this.save(); this.save();
} }
onTitleAudioUploadSuccess(e) {
this.item.contentObj.titleAudio_url = e.url;
this.save();
}
addItem() {
let item = this.cardItemData();
this.dataArray.push(item);
this.saveItem();
}
radioClick(it, radioValue) {
it.radioValue = radioValue;
this.saveItem();
}
clickCheckBox() {
this.saveItem();
}
saveItem() {
this.save();
}
/**
* 储存数据
*/
save() { save() {
(<any> window).courseware.setData(this.item, null, this.saveKey); (<any> window).courseware.setData(this.item, null, this.KEY);
this.refresh(); this.refresh();
console.log(this.item)
} }
/**
* 刷新 渲染页面
*/
refresh() { refresh() {
setTimeout(() => { setTimeout(() => {
this.appRef.tick(); this.appRef.tick();
......
import {
MySprite,
getMinScale,
ShapeRect,
tweenChange,
randomSortByArr,
Label,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem,
ShapeRectNew
} from "./Unit";
import { CartoonAnimation } from './CartoonAnimation'
export class Cartoon {
// 系统缩放比例
mapScale = 1;
stageWidth;
stageHeight;
clientWidth;
clientHeight;
// 音乐 和 图片的缓冲区
audio = new Map();
images = new Map();
imagesOriginSize = new Map();
// 坐标原点 包含缩放
originX = 0;
originY = 0;
setOrigin = (x, y)=>{
this.originX = x;
this.originY = y;
}
getOrigin = ()=>{
return {
x: this.originX,
y: this.originY
}
}
// 相对坐标原点 包含缩放 用于添加孩子动画元素
relativeOriginX = 0;
relativeOriginY = 0;
setRelativeOrigin = (x, y)=>{
this.relativeOriginX = x;
this.relativeOriginY = y;
}
getRelativeOrigin = ()=>{
return {
x: this.relativeOriginX,
y: this.relativeOriginY
}
}
// 存放音乐和图片的地址
audioObj = {}
imageObj = {}
_currentPlayAudio;
// 添加音乐
addAudio = ( key, url ) => {
this.audioObj[key] = url
};
// 添加音乐
addImage = ( key, url ) => {
this.imageObj[key] = url
};
// 播放音乐
_playingNow = []
playAudio = function( key, now = false, callback = null) {
const audio = this.audio.get(key);
if (audio) {
if (now) {
audio.pause();
audio.currentTime = 0;
}
if (callback) {
audio.onended = () => {
let index = this._playingNow.indexOf(audio)
if(index != -1){
this._playingNow.splice(index,1)
}
callback();
};
}
audio.play();
audio.callback = callback
this._playingNow.push(audio)
this._currentPlayAudio = audio;
}
}
stopAllAudio(){
this._playingNow.forEach(audio=>{
audio.onended && audio.onended()
audio.pause();
audio.currentTime = 0;
})
this._playingNow = []
}
stopAudio(){
if(this._currentPlayAudio){
this._currentPlayAudio.pause();
this._currentPlayAudio.currentTime = 0;
}
}
// 异步加载图片 音频资源
loadResources = ()=> {
const pr = [];
for(let key in this.imageObj){
const p = this.preloadImage(this.imageObj[key]).then( (img:any) => {
this.images.set(key, img);
this.imagesOriginSize.set(key, {width:img.width, height:img.height});
}).catch(err => console.log(key));
pr.push(p);
};
for(let key in this.audioObj){
const a = this.preloadAudio(this.audioObj[key]).then( (audio:any) => {
this.audio.set(key, audio);
}).catch(err => console.log(key));
pr.push(a);
};
return Promise.all(pr);
}
// 预加载图片
preloadImage = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
}
// 预加载音频
preloadAudio = (url) => {
return new Promise((resolve, reject) => {
const audio = new Audio();
audio.oncanplay = a => {
resolve(audio);
};
audio.onerror = () => {
reject();
};
audio.src = url;
audio.load();
});
}
// 缓存页面元素
cartoonElementsBuffer = {}
createCartoonElement = (key, type, width?:number, heigth?:number, initX?:number, initY?:number)=>{
this.cartoonElementsBuffer[key] = {}
this.cartoonElementsBuffer[key].id = key;
this.cartoonElementsBuffer[key].width = width;
this.cartoonElementsBuffer[key].heigth = heigth;
this.cartoonElementsBuffer[key].width = width;
this.cartoonElementsBuffer[key].heigth = heigth;
this.cartoonElementsBuffer[key].x = initX;
this.cartoonElementsBuffer[key].y = initY;
switch(type){
case "MySprite": this.cartoonElementsBuffer[key].ref = new MySprite(); break;
case "ShapeRect": this.cartoonElementsBuffer[key].ref = new ShapeRect(); break;
case "ShapeRectNew": this.cartoonElementsBuffer[key].ref = new ShapeRectNew(); break;
case "Label": this.cartoonElementsBuffer[key].ref = new Label(); break;
default : this.cartoonElementsBuffer[key].ref = new MySprite(); break;
}
this.cartoonElementsBuffer[key].ref.x = initX;
this.cartoonElementsBuffer[key].ref.y = initY;
this.cartoonElementsBuffer[key].animation = new CartoonAnimation(this.cartoonElementsBuffer[key].ref)
return this.cartoonElementsBuffer[key]
}
createElement = (type, initX?:number, initY?:number)=>{
let element;
switch(type){
case "MySprite": element = new MySprite(); break;
case "ShapeRect": element = new ShapeRect(); break;
default : element = new MySprite(); break;
}
element.x = initX;
element.y = initY;
return element
}
createLabel = ({
text,
fontName,
fontColor,
fontSize,
textAlign
}, initX?, initY?)=>{
let element = new Label()
element.text = text;
element.fontName = fontName;
element.fontColor = fontColor;
element.fontSize = fontSize;
element.textAlign = textAlign;
element.x = initX;
element.y = initY;
return element
}
getCartoonElementRef = (key)=>{
if(this.cartoonElementsBuffer[key]){
return this.cartoonElementsBuffer[key].ref;
}else{
return undefined
}
}
getCartoonElement = (key)=>{
return this.cartoonElementsBuffer[key]
}
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
}
}
animation = new CartoonAnimation(this)
}
\ No newline at end of file
import {
MySprite,
getMinScale,
ShapeRect,
tweenChange,
randomSortByArr,
Label,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem
} from "./Unit";
export class CartoonAnimation {
animations = {}
currentRef;
constructor(ref){
this.currentRef = ref
}
add(key:string, func:Function){
this.animations[key] = func
}
move = (ele, distPosition, runTime, callback?:Function )=>{
tweenChange(ele, distPosition, runTime, ()=>{
callback && callback()
});
}
scaleChange = this.move;
run( key:string ){
this.animations[key]()
}
overCard = function (callback?: any){
let w = this.currentRef.scaleX;
this.scaleChange(this.currentRef, { scaleX: 0 }, 0.3, () => {
this.currentRef.frontSide.visible = !this.currentRef.frontSide.visible;
this.currentRef.backSide.visible = !this.currentRef.backSide.visible;
this.scaleChange(this.currentRef, { scaleX: w }, 0.3, () => {
callback && callback();
});
});
}
}
\ No newline at end of file
import TWEEN from "@tweenjs/tween.js";
import TWEEN from '@tweenjs/tween.js'; import { del } from "selenium-webdriver/http";
import construct = Reflect.construct;
interface AirWindow extends Window {
air: any;
curCtx: any;
}
declare let window: AirWindow;
class Sprite { class Sprite {
x = 0; x = 0;
y = 0; y = 0;
color = ''; color = "";
radius = 0; radius = 0;
alive = false; alive = false;
margin = 0; margin = 0;
angle = 0; angle = 0;
ctx; ctx;
id;
constructor(ctx = null) { constructor(ctx = null) {
if (!ctx) { if (!ctx) {
this.ctx = window.curCtx; this.ctx = window["curCtx"];
} else { } else {
this.ctx = ctx; this.ctx = ctx;
} }
...@@ -27,18 +22,10 @@ class Sprite { ...@@ -27,18 +22,10 @@ class Sprite {
update($event) { update($event) {
this.draw(); this.draw();
} }
draw() { draw() {}
}
} }
export class MySprite extends Sprite { export class MySprite extends Sprite {
_width = 0; _width = 0;
_height = 0; _height = 0;
_anchorX = 0; _anchorX = 0;
...@@ -53,14 +40,6 @@ export class MySprite extends Sprite { ...@@ -53,14 +40,6 @@ export class MySprite extends Sprite {
skewX = 0; skewX = 0;
skewY = 0; skewY = 0;
_shadowFlag = false;
_shadowColor;
_shadowOffsetX = 0;
_shadowOffsetY = 0;
_shadowBlur = 5;
_radius = 0;
children = [this]; children = [this];
childDepandVisible = true; childDepandVisible = true;
...@@ -69,50 +48,26 @@ export class MySprite extends Sprite { ...@@ -69,50 +48,26 @@ export class MySprite extends Sprite {
img; img;
_z = 0; _z = 0;
init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) { init(imgObj = null, anchorX: number = 0.5, anchorY: number = 0.5) {
if (imgObj) { if (imgObj) {
this.img = imgObj; this.img = imgObj;
this.width = this.img.width; this.width = this.img.width;
this.height = this.img.height; this.height = this.img.height;
} }
this.anchorX = anchorX; this.anchorX = anchorX;
this.anchorY = anchorY; this.anchorY = anchorY;
} }
setShadow(offX, offY, blur, color = 'rgba(0, 0, 0, 0.3)') {
this._shadowFlag = true;
this._shadowColor = color;
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
this._shadowBlur = blur;
}
setRadius(r) {
this._radius = r;
}
update($event = null) { update($event = null) {
if (!this.visible && this.childDepandVisible) { if (!this.visible && this.childDepandVisible) {
return; return;
} }
this.draw(); this.draw();
} }
draw() { draw() {
this.ctx.save(); this.ctx.save();
this.drawInit(); this.drawInit();
...@@ -120,95 +75,49 @@ export class MySprite extends Sprite { ...@@ -120,95 +75,49 @@ export class MySprite extends Sprite {
this.updateChildren(); this.updateChildren();
this.ctx.restore(); this.ctx.restore();
} }
drawInit() { drawInit() {
this.ctx.translate(this.x, this.y); this.ctx.translate(this.x, this.y);
this.ctx.rotate(this.rotation * Math.PI / 180); this.ctx.rotate((this.rotation * Math.PI) / 180);
this.ctx.scale(this.scaleX, this.scaleY); this.ctx.scale(this.scaleX, this.scaleY);
this.ctx.globalAlpha = this.alpha; this.ctx.globalAlpha = this.alpha;
this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0); this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0);
if (this._radius) {
const r = this._radius;
const w = this.width;
const h = this.height;
this.ctx.lineTo(-w / 2, h / 2); // 创建水平线
this.ctx.arcTo(-w / 2, -h / 2, -w / 2 + r, -h / 2, r);
this.ctx.arcTo(w / 2, -h / 2, w / 2, -h / 2 + r, r);
this.ctx.arcTo(w / 2, h / 2, w / 2 - r, h / 2, r);
this.ctx.arcTo(-w / 2, h / 2, -w / 2, h / 2 - r, r);
this.ctx.clip();
}
} }
drawSelf() { drawSelf() {
if (this._shadowFlag) {
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
this.ctx.shadowBlur = this._shadowBlur;
this.ctx.shadowColor = this._shadowColor;
} else {
this.ctx.shadowOffsetX = 0;
this.ctx.shadowOffsetY = 0;
this.ctx.shadowBlur = null;
this.ctx.shadowColor = null;
}
if (this.img) { if (this.img) {
this.ctx.drawImage(this.img, this._offX, this._offY); this.ctx.drawImage(this.img, this._offX, this._offY);
} }
} }
updateChildren() { updateChildren() {
if (this.children.length <= 0) {
return;
}
if (this.children.length <= 0) { return; } for (let i = 0; i < this.children.length; i++) {
if (this.children[i] === this) {
for (const child of this.children) {
if (child === this) {
if (this.visible) { if (this.visible) {
this.drawSelf(); this.drawSelf();
} }
} else { } else {
child.update(); this.children[i].update();
} }
} }
} }
load(url, anchorX = 0.5, anchorY = 0.5) { load(url, anchorX = 0.5, anchorY = 0.5) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const img = new Image(); const img = new Image();
img.onload = () => resolve(img); img.onload = () => resolve(img);
img.onerror = reject; img.onerror = reject;
img.src = url; img.src = url;
}).then(img => { }).then(img => {
this.init(img, anchorX, anchorY); this.init(img, anchorX, anchorY);
return img; return img;
}); });
...@@ -225,11 +134,9 @@ export class MySprite extends Sprite { ...@@ -225,11 +134,9 @@ export class MySprite extends Sprite {
return a._z - b._z; return a._z - b._z;
}); });
if (this.childDepandAlpha) { if (this.childDepandAlpha) {
child.alpha = this.alpha; child.alpha = this.alpha;
} }
} }
removeChild(child) { removeChild(child) {
const index = this.children.indexOf(child); const index = this.children.indexOf(child);
...@@ -241,18 +148,18 @@ export class MySprite extends Sprite { ...@@ -241,18 +148,18 @@ export class MySprite extends Sprite {
removeChildren() { removeChildren() {
for (let i = 0; i < this.children.length; i++) { for (let i = 0; i < this.children.length; i++) {
if (this.children[i]) { if (this.children[i]) {
if (this.children[i] !== this) { if (this.children[i] != this) {
this.children.splice(i, 1); this.children.splice(i, 1);
i --; i--;
} }
} }
} }
} }
_changeChildAlpha(alpha) { _changeChildAlpha(alpha) {
for (const child of this.children) { for (let i = 0; i < this.children.length; i++) {
if (child !== this) { if (this.children[i] != this) {
child.alpha = alpha; this.children[i].alpha = alpha;
} }
} }
} }
...@@ -304,10 +211,7 @@ export class MySprite extends Sprite { ...@@ -304,10 +211,7 @@ export class MySprite extends Sprite {
} }
getBoundingBox() { getBoundingBox() {
const getParentData = item => {
const getParentData = (item) => {
let px = item.x; let px = item.x;
let py = item.y; let py = item.y;
...@@ -315,7 +219,6 @@ export class MySprite extends Sprite { ...@@ -315,7 +219,6 @@ export class MySprite extends Sprite {
let sy = item.scaleY; let sy = item.scaleY;
const parent = item.parent; const parent = item.parent;
if (parent) { if (parent) {
const obj = getParentData(parent); const obj = getParentData(parent);
const _x = obj.px; const _x = obj.px;
...@@ -328,16 +231,13 @@ export class MySprite extends Sprite { ...@@ -328,16 +231,13 @@ export class MySprite extends Sprite {
sx *= _sx; sx *= _sx;
sy *= _sy; sy *= _sy;
} }
return {px, py, sx, sy}; return { px, py, sx, sy };
}; };
const data = getParentData(this); const data = getParentData(this);
const x = data.px + this._offX * Math.abs(data.sx); const x = data.px + this._offX * Math.abs(data.sx);
const y = data.py + this._offY * Math.abs(data.sy); const y = data.py + this._offY * Math.abs(data.sy);
const width = this.width * Math.abs(data.sx); const width = this.width * Math.abs(data.sx);
...@@ -348,40 +248,29 @@ export class MySprite extends Sprite { ...@@ -348,40 +248,29 @@ export class MySprite extends Sprite {
// const width = this.width * Math.abs(this.scaleX); // const width = this.width * Math.abs(this.scaleX);
// const height = this.height * Math.abs(this.scaleY); // const height = this.height * Math.abs(this.scaleY);
return {x, y, width, height}; return { x, y, width, height };
} }
} }
export class ColorSpr extends MySprite { export class ColorSpr extends MySprite {
r = 0; r = 0;
g = 0; g = 0;
b = 0; b = 0;
createGSCanvas() { createGSCanvas() {
if (!this.img) { if (!this.img) {
return; return;
} }
const rect = this.getBoundingBox(); const rect = this.getBoundingBox();
if (rect.width <= 1 || rect.height <= 1) { if (rect.width <= 1 || rect.height <= 1) {
return; return;
} }
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height); const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for ( let i = 0; i < c.height; i++) { for (let i = 0; i < c.height; i++) {
for ( let j = 0; j < c.width; j++) { for (let j = 0; j < c.width; j++) {
const x = i * 4 * c.width + j * 4;
const x = (i * 4) * c.width + ( j * 4 );
const r = c.data[x]; const r = c.data[x];
const g = c.data[x + 1]; const g = c.data[x + 1];
const b = c.data[x + 2]; const b = c.data[x + 2];
...@@ -390,8 +279,6 @@ export class ColorSpr extends MySprite { ...@@ -390,8 +279,6 @@ export class ColorSpr extends MySprite {
c.data[x + 1] = this.g; c.data[x + 1] = this.g;
c.data[x + 2] = this.b; c.data[x + 2] = this.b;
// c.data[x] = c.data[x + 1] = c.data[x + 2] = (r + g + b) / 3 ; // c.data[x] = c.data[x + 1] = c.data[x + 2] = (r + g + b) / 3 ;
// // c.data[x + 3] = 255; // // c.data[x + 3] = 255;
} }
...@@ -400,34 +287,26 @@ export class ColorSpr extends MySprite { ...@@ -400,34 +287,26 @@ export class ColorSpr extends MySprite {
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height); this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.createGSCanvas(); this.createGSCanvas();
} }
} }
export class GrayscaleSpr extends MySprite { export class GrayscaleSpr extends MySprite {
grayScale = 120; grayScale = 120;
createGSCanvas() { createGSCanvas() {
if (!this.img) { if (!this.img) {
return; return;
} }
const rect = this.getBoundingBox(); const rect = this.getBoundingBox();
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height); const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for ( let i = 0; i < c.height; i++) { for (let i = 0; i < c.height; i++) {
for ( let j = 0; j < c.width; j++) { for (let j = 0; j < c.width; j++) {
const x = i * 4 * c.width + j * 4;
const x = (i * 4) * c.width + ( j * 4 );
const r = c.data[x]; const r = c.data[x];
const g = c.data[x + 1]; const g = c.data[x + 1];
const b = c.data[x + 2]; const b = c.data[x + 2];
...@@ -441,37 +320,26 @@ export class GrayscaleSpr extends MySprite { ...@@ -441,37 +320,26 @@ export class GrayscaleSpr extends MySprite {
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height); this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.createGSCanvas(); this.createGSCanvas();
} }
} }
export class BitMapLabel extends MySprite { export class BitMapLabel extends MySprite {
labelArr; labelArr;
baseUrl; baseUrl;
setText(data, text) { setText(data, text) {
this.labelArr = []; this.labelArr = [];
const labelArr = []; const labelArr = [];
const tmpArr = text.split(''); const tmpArr = text.split("");
let totalW = 0; let totalW = 0;
let h = 0; let h = 0;
for (const tmp of tmpArr) { for (let i = 0; i < tmpArr.length; i++) {
const label = new MySprite(this.ctx); const label = new MySprite(this.ctx);
label.init(data[tmp], 0); label.init(data[tmpArr[i]], 0);
this.addChild(label); this.addChild(label);
labelArr.push(label); labelArr.push(label);
...@@ -479,60 +347,52 @@ export class BitMapLabel extends MySprite { ...@@ -479,60 +347,52 @@ export class BitMapLabel extends MySprite {
h = label.height; h = label.height;
} }
this.width = totalW; this.width = totalW;
this.height = h; this.height = h;
let offX = -totalW / 2; let offX = -totalW / 2;
for (const label of labelArr) { for (let i = 0; i < labelArr.length; i++) {
label.x = offX; labelArr[i].x = offX;
offX += label.width; offX += labelArr[i].width;
} }
this.labelArr = labelArr; this.labelArr = labelArr;
} }
} }
export class Label extends MySprite { export class Label extends MySprite {
text: String;
text: string;
// fontSize:String = '40px'; // fontSize:String = '40px';
fontName = 'Verdana'; fontName: String = "Verdana";
textAlign = 'left'; textAlign: String = "left";
fontSize = 40; fontSize = 40;
fontColor = '#000000'; fontColor = "#000000";
fontWeight = 900; fontWeight = 900;
_maxWidth; maxWidth;
outline = 0; outline = 0;
outlineColor = '#ffffff'; outlineColor = "#ffffff";
maxSingalLineWidth = 0;
// _shadowFlag = false; _shadowFlag = false;
// _shadowColor; _shadowColor;
// _shadowOffsetX; _shadowOffsetX;
// _shadowOffsetY; _shadowOffsetY;
// _shadowBlur; _shadowBlur;
_outlineFlag = false; _outlineFlag = false;
_outLineWidth; _outLineWidth;
_outLineColor; _outLineColor;
_warpLineY = 0;
constructor(ctx = null) { constructor(ctx = null) {
super(ctx); super(ctx);
this.init(); this.init();
} }
refreshSize() { refreshSize() {
this.ctx.save(); this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
this._width = this.ctx.measureText(this.text).width; this._width = this.ctx.measureText(this.text).width;
...@@ -540,12 +400,10 @@ export class Label extends MySprite { ...@@ -540,12 +400,10 @@ export class Label extends MySprite {
this.refreshAnchorOff(); this.refreshAnchorOff();
this.ctx.restore(); this.ctx.restore();
} }
setMaxSize(w) { setMaxSize(w) {
this.maxWidth = w;
this._maxWidth = w;
this.refreshSize(); this.refreshSize();
if (this.width >= w) { if (this.width >= w) {
this.scaleX *= w / this.width; this.scaleX *= w / this.width;
...@@ -554,7 +412,6 @@ export class Label extends MySprite { ...@@ -554,7 +412,6 @@ export class Label extends MySprite {
} }
show(callBack = null) { show(callBack = null) {
this.visible = true; this.visible = true;
if (this.alpha >= 1) { if (this.alpha >= 1) {
...@@ -564,7 +421,7 @@ export class Label extends MySprite { ...@@ -564,7 +421,7 @@ export class Label extends MySprite {
const tween = new TWEEN.Tween(this) const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800) .to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function() {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -572,47 +429,41 @@ export class Label extends MySprite { ...@@ -572,47 +429,41 @@ export class Label extends MySprite {
.start(); // Start the tween immediately. .start(); // Start the tween immediately.
} }
// setShadow(offX = 0, offY = 2, blur = 2, color = 'rgba(0, 0, 0, 0.2)') { setShadow(offX = 2, offY = 2, blur = 2, color = "rgba(0, 0, 0, 0.2)") {
// this._shadowFlag = true;
// this._shadowFlag = true; this._shadowColor = color;
// this._shadowColor = color; // 将阴影向右移动15px,向上移动10px
// // 将阴影向右移动15px,向上移动10px this._shadowOffsetX = offX;
// this._shadowOffsetX = 5; this._shadowOffsetY = offY;
// this._shadowOffsetY = 5; // 轻微模糊阴影
// // 轻微模糊阴影 this._shadowBlur = blur;
// this._shadowBlur = 5; }
// }
setOutline(width = 5, color = '#ffffff') {
setOutline(width = 5, color = "#ffffff") {
this._outlineFlag = true; this._outlineFlag = true;
this._outLineWidth = width; this._outLineWidth = width;
this._outLineColor = color; this._outLineColor = color;
} }
drawText() { drawText() {
// console.log('in drawText', this.text); // console.log('in drawText', this.text);
if (!this.text) { return; } if (!this.text) {
return;
}
// if (this._shadowFlag) {
//
// this.ctx.shadowColor = this._shadowColor;
// // 将阴影向右移动15px,向上移动10px
// this.ctx.shadowOffsetX = this._shadowOffsetX;
// this.ctx.shadowOffsetY = this._shadowOffsetY;
// // 轻微模糊阴影
// this.ctx.shadowBlur = this._shadowBlur;
// }
if (this._shadowFlag) {
this.ctx.shadowColor = this._shadowColor;
// 将阴影向右移动15px,向上移动10px
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
// 轻微模糊阴影
this.ctx.shadowBlur = this._shadowBlur;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
if (this._outlineFlag) { if (this._outlineFlag) {
...@@ -623,61 +474,152 @@ export class Label extends MySprite { ...@@ -623,61 +474,152 @@ export class Label extends MySprite {
this.ctx.fillStyle = this.fontColor; this.ctx.fillStyle = this.fontColor;
if (this.outline > 0) { if (this.outline > 0) {
this.ctx.lineWidth = this.outline; this.ctx.lineWidth = this.outline;
this.ctx.strokeStyle = this.outlineColor; this.ctx.strokeStyle = this.outlineColor;
this.ctx.strokeText(this.text, 0, 0); this.ctx.strokeText(this.text, 0, 0);
} }
// 当maxSingalLineWidth不为0时,对数据进行换行处理
if(this.maxSingalLineWidth !== 0 ){
var words = this.text.split(' ');
var line = '';
this._warpLineY = 0;
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = this.ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > this.maxSingalLineWidth && n > 0) {
this.ctx.fillText(line, 0, this._warpLineY);
line = words[n] + ' ';
this._warpLineY += this.fontSize;
}
else {
line = testLine;
}
}
this.y = -this._warpLineY /2
this.ctx.fillText(line, 0, this._warpLineY);
}else{
this.ctx.fillText(this.text, 0, 0); this.ctx.fillText(this.text, 0, 0);
}
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class ShapeRectNew extends MySprite {
radius = 0;
fillColor = '#ffffff';
strokeColor = '#000000';
fill = true;
stroke = false;
lineWidth = 1;
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
drawShape() {
const ctx = this.ctx;
const width = this.width;
const height = this.height;
const radius = this.radius;
ctx.save();
ctx.beginPath(0);
// 从右下角顺时针绘制,弧度从0到1/2PI
ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
// 矩形下边线
ctx.lineTo(radius, height);
// 左下角圆弧,弧度从1/2PI到PI
ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
// 矩形左边线
ctx.lineTo(0, radius);
// 左上角圆弧,弧度从PI到3/2PI
ctx.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
// 上边线
ctx.lineTo(width - radius, 0);
// 右上角圆弧
ctx.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
// 右边线
ctx.lineTo(width, height - radius);
ctx.closePath();
if (this.fill) {
ctx.fillStyle = this.fillColor;
ctx.fill();
}
if (this.stroke) {
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.strokeColor;
ctx.stroke();
}
ctx.restore();
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawText(); this.drawShape();
} }
} }
export class RichTextOld extends Label { export class RichTextOld extends Label {
textArr = []; textArr = [];
fontSize = 40; fontSize = 40;
setText(text: string, words) { setText(text: string, words) {
let newText = text; let newText = text;
for (const word of words) { for (let i = 0; i < words.length; i++) {
const word = words[i];
const re = new RegExp(word, 'g'); const re = new RegExp(word, "g");
newText = newText.replace( re, `#${word}#`); newText = newText.replace(re, `#${word}#`);
// newText = newText.replace(word, `#${word}#`); // newText = newText.replace(word, `#${word}#`);
} }
this.textArr = newText.split('#'); this.textArr = newText.split("#");
this.text = newText; this.text = newText;
// this.setSize(); // this.setSize();
} }
refreshSize() { refreshSize() {
this.ctx.save(); this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
let curX = 0; let curX = 0;
for (const text of this.textArr) { for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(text).width; const w = this.ctx.measureText(this.textArr[i]).width;
curX += w; curX += w;
} }
...@@ -686,12 +628,9 @@ export class RichTextOld extends Label { ...@@ -686,12 +628,9 @@ export class RichTextOld extends Label {
this.refreshAnchorOff(); this.refreshAnchorOff();
this.ctx.restore(); this.ctx.restore();
} }
show(callBack = null) { show(callBack = null) {
// console.log(' in show '); // console.log(' in show ');
this.visible = true; this.visible = true;
// this.alpha = 0; // this.alpha = 0;
...@@ -699,185 +638,119 @@ export class RichTextOld extends Label { ...@@ -699,185 +638,119 @@ export class RichTextOld extends Label {
const tween = new TWEEN.Tween(this) const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800) .to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function() {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
}) })
.start(); // Start the tween immediately. .start(); // Start the tween immediately.
} }
drawText() { drawText() {
// console.log('in drawText', this.text); // console.log('in drawText', this.text);
if (!this.text) { return; } if (!this.text) {
return;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = 900; this.ctx.fontWeight = 900;
this.ctx.lineWidth = 5; this.ctx.lineWidth = 5;
this.ctx.strokeStyle = '#ffffff'; this.ctx.strokeStyle = "#ffffff";
// this.ctx.strokeText(this.text, 0, 0); // this.ctx.strokeText(this.text, 0, 0);
this.ctx.fillStyle = '#000000'; this.ctx.fillStyle = "#000000";
// this.ctx.fillText(this.text, 0, 0); // this.ctx.fillText(this.text, 0, 0);
let curX = 0; let curX = 0;
for (let i = 0; i < this.textArr.length; i++) { for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width; const w = this.ctx.measureText(this.textArr[i]).width;
if ((i + 1) % 2 === 0) { if ((i + 1) % 2 == 0) {
this.ctx.fillStyle = '#c8171e'; this.ctx.fillStyle = "#c8171e";
} else { } else {
this.ctx.fillStyle = '#000000'; this.ctx.fillStyle = "#000000";
} }
this.ctx.fillText(this.textArr[i], curX, 0); this.ctx.fillText(this.textArr[i], curX, 0);
curX += w; curX += w;
} }
} }
} }
export class RichText extends Label { export class RichText extends Label {
disH = 30; disH = 30;
constructor(ctx?: any) { constructor(ctx) {
super(ctx); super(ctx);
// this.dataArr = dataArr; // this.dataArr = dataArr;
} }
drawText() { drawText() {
if (!this.text) { if (!this.text) {
return; return;
} }
this.ctx.font = `${this.fontSize}px ${this.fontName}`; this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign; this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle'; this.ctx.textBaseline = "middle";
this.ctx.fontWeight = this.fontWeight; this.ctx.fontWeight = this.fontWeight;
this.ctx.fillStyle = this.fontColor; this.ctx.fillStyle = this.fontColor;
const selfW = this.width * this.scaleX; const selfW = this.width * this.scaleX;
const chr = this.text.split(" ");
const chr = this.text.split(' '); let temp = "";
let temp = '';
const row = []; const row = [];
const w = selfW - 80; const w = selfW - 80;
const disH = (this.fontSize + this.disH) * this.scaleY; const disH = (this.fontSize + this.disH) * this.scaleY;
for (let a = 0; a < chr.length; a++) {
if (
this.ctx.measureText(temp).width < w &&
for (const c of chr) { this.ctx.measureText(temp + chr[a]).width <= w
if (this.ctx.measureText(temp).width < w && this.ctx.measureText(temp + (c)).width <= w) { ) {
temp += ' ' + c; temp += " " + chr[a];
} else { } else {
row.push(temp); row.push(temp);
temp = ' ' + c; temp = " " + chr[a];
} }
} }
row.push(temp); row.push(temp);
const x = 0; const x = 0;
const y = -row.length * disH / 2; const y = (-row.length * disH) / 2;
// for (let b = 0 ; b < row.length; b++) { // for (let b = 0 ; b < row.length; b++) {
// this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20 // this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20
// } // }
if (this._outlineFlag) { if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth; this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor; this.ctx.strokeStyle = this._outLineColor;
for (let b = 0 ; b < row.length; b++) { for (let b = 0; b < row.length; b++) {
this.ctx.strokeText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20 this.ctx.strokeText(row[b], x, y + (b + 1) * disH); // 每行字体y坐标间隔20
} }
// this.ctx.strokeText(this.text, 0, 0); // this.ctx.strokeText(this.text, 0, 0);
} }
// this.ctx.fillStyle = '#ff7600'; // this.ctx.fillStyle = '#ff7600';
for (let b = 0 ; b < row.length; b++) { for (let b = 0; b < row.length; b++) {
this.ctx.fillText(row[b], x, y + ( b + 1 ) * disH ); // 每行字体y坐标间隔20 this.ctx.fillText(row[b], x, y + (b + 1) * disH); // 每行字体y坐标间隔20
} }
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawText(); this.drawText();
} }
}
export class LineRect extends MySprite {
lineColor = '#ffffff';
lineWidth = 10;
setSize(w, h) {
this.width = w;
this.height = h;
}
drawLine() {
this.ctx.beginPath();
this.ctx.moveTo(this._offX, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY);
this.ctx.lineTo(this._offX + this.width, this._offY + this.height);
this.ctx.lineTo(this._offX, this._offY + this.height);
this.ctx.closePath();
this.ctx.lineWidth = this.lineWidth;
// this.ctx.fillStyle = "rgb(2,33,42)"; //指定填充颜色
// this.ctx.fill(); //对多边形进行填充
this.ctx.strokeStyle = this.lineColor; // "#ffffff";
this.ctx.stroke();
}
drawSelf() {
super.drawSelf();
this.drawLine();
}
} }
export class ShapeRect extends MySprite { export class ShapeRect extends MySprite {
fillColor = "#FF0000";
fillColor = '#FF0000';
setSize(w, h) { setSize(w, h) {
this.width = w; this.width = w;
...@@ -888,136 +761,64 @@ export class ShapeRect extends MySprite { ...@@ -888,136 +761,64 @@ export class ShapeRect extends MySprite {
} }
drawShape() { drawShape() {
this.ctx.fillStyle = this.fillColor; this.ctx.fillStyle = this.fillColor;
this.ctx.fillRect(this._offX, this._offY, this.width, this.height); this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawShape(); this.drawShape();
} }
} }
export class ShapeCircle extends MySprite { export class ShapeCircle extends MySprite {
fillColor = "#FF0000";
fillColor = '#FF0000';
radius = 0; radius = 0;
startRadian = 0;
endRadian = 180;
strokeLineWidth = 5;
strokeColor = "#702dee";
drawType = "fill"
counterclockwise = false; // false 逆时针 true 顺时针
setRadius(r) { setRadius(r) {
this.anchorX = this.anchorY = 0.5; this.anchorX = this.anchorY = 0.5;
this.radius = r; this.radius = r;
this.width = r * 2; this.width = r * 2;
this.height = r * 2; this.height = r * 2;
} }
drawShape() { drawShape() {
switch(this.drawType){
case "stroke":
this.ctx.beginPath(); this.ctx.beginPath();
this.ctx.fillStyle = this.fillColor; this.ctx.strokeStyle = this.strokeColor;
this.ctx.arc(0, 0, this.radius, 0, angleToRadian(360)); this.ctx.lineWidth = this.strokeLineWidth
this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian, this.counterclockwise);
this.ctx.stroke()
break;
default:
this.ctx.beginPath();
this.ctx.fillColor = this.fillColor;
this.ctx.arc(0, 0, this.radius, this.startRadian, this.endRadian);
this.ctx.fill(); this.ctx.fill();
break;
} }
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class ShapeRectNew extends MySprite {
radius = 0;
fillColor = '#ffffff';
strokeColor = '#000000';
fill = true;
stroke = false;
lineWidth = 1;
setSize(w, h, r) {
this.width = w;
this.height = h;
this.radius = r;
}
setOutLine(color, lineWidth) {
this.stroke = true;
this.strokeColor = color;
this.lineWidth = lineWidth;
}
drawShape() {
const ctx = this.ctx;
const width = this.width;
const height = this.height;
const radius = this.radius;
ctx.save();
ctx.beginPath(0);
// 从右下角顺时针绘制,弧度从0到1/2PI
ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
// 矩形下边线
ctx.lineTo(radius, height);
// 左下角圆弧,弧度从1/2PI到PI
ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
// 矩形左边线
ctx.lineTo(0, radius);
// 左上角圆弧,弧度从PI到3/2PI
ctx.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
// 上边线
ctx.lineTo(width - radius, 0);
// 右上角圆弧
ctx.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
// 右边线
ctx.lineTo(width, height - radius);
ctx.closePath();
if (this.fill) {
ctx.fillStyle = this.fillColor;
ctx.fill();
}
if (this.stroke) {
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.strokeColor;
ctx.stroke();
}
ctx.restore();
} }
drawSelf() { drawSelf() {
super.drawSelf(); super.drawSelf();
this.drawShape(); this.drawShape();
} }
} }
export class MyAnimation extends MySprite {
export class MyAnimation extends MySprite {
frameArr = []; frameArr = [];
frameIndex = 0; frameIndex = 0;
playFlag = false; playFlag = false;
lastDateTime; lastDateTime;
curDelay = 0; curDelay = 0;
loop = false; loop = false;
playEndFunc; playEndFunc;
delayPerUnit = 1; delayPerUnit = 1;
...@@ -1026,7 +827,6 @@ export class MyAnimation extends MySprite { ...@@ -1026,7 +827,6 @@ export class MyAnimation extends MySprite {
reverseFlag = false; reverseFlag = false;
addFrameByImg(img) { addFrameByImg(img) {
const spr = new MySprite(this.ctx); const spr = new MySprite(this.ctx);
spr.init(img); spr.init(img);
this._refreshSize(img); this._refreshSize(img);
...@@ -1040,10 +840,8 @@ export class MyAnimation extends MySprite { ...@@ -1040,10 +840,8 @@ export class MyAnimation extends MySprite {
} }
addFrameByUrl(url) { addFrameByUrl(url) {
const spr = new MySprite(this.ctx); const spr = new MySprite(this.ctx);
spr.load(url).then(img => { spr.load(url).then(img => {
this._refreshSize(img); this._refreshSize(img);
}); });
spr.visible = false; spr.visible = false;
...@@ -1054,18 +852,15 @@ export class MyAnimation extends MySprite { ...@@ -1054,18 +852,15 @@ export class MyAnimation extends MySprite {
this.frameArr[this.frameIndex].visible = true; this.frameArr[this.frameIndex].visible = true;
} }
_refreshSize(img: any) { _refreshSize(img) {
if (this.width < img["width"]) {
if (this.width < img.width) { this.width = img["width"];
this.width = img.width;
} }
if (this.height < img.height) { if (this.height < img["height"]) {
this.height = img.height; this.height = img["height"];
} }
} }
play() { play() {
this.playFlag = true; this.playFlag = true;
this.lastDateTime = new Date().getTime(); this.lastDateTime = new Date().getTime();
...@@ -1075,13 +870,11 @@ export class MyAnimation extends MySprite { ...@@ -1075,13 +870,11 @@ export class MyAnimation extends MySprite {
this.playFlag = false; this.playFlag = false;
} }
replay() { replay() {
this.restartFlag = true; this.restartFlag = true;
this.play(); this.play();
} }
reverse() { reverse() {
this.reverseFlag = !this.reverseFlag; this.reverseFlag = !this.reverseFlag;
this.frameArr.reverse(); this.frameArr.reverse();
...@@ -1089,20 +882,18 @@ export class MyAnimation extends MySprite { ...@@ -1089,20 +882,18 @@ export class MyAnimation extends MySprite {
} }
showAllFrame() { showAllFrame() {
for (const frame of this.frameArr ) { for (let i = 0; i < this.frameArr.length; i++) {
frame.alpha = 1; this.frameArr[i].alpha = 1;
} }
} }
hideAllFrame() { hideAllFrame() {
for (const frame of this.frameArr) { for (let i = 0; i < this.frameArr.length; i++) {
frame.alpha = 0; this.frameArr[i].alpha = 0;
} }
} }
playEnd() { playEnd() {
this.playFlag = false; this.playFlag = false;
this.curDelay = 0; this.curDelay = 0;
...@@ -1119,7 +910,7 @@ export class MyAnimation extends MySprite { ...@@ -1119,7 +910,7 @@ export class MyAnimation extends MySprite {
this.frameArr[this.frameIndex].visible = false; this.frameArr[this.frameIndex].visible = false;
} }
this.frameIndex ++; this.frameIndex++;
if (this.frameIndex >= this.frameArr.length) { if (this.frameIndex >= this.frameArr.length) {
if (this.loop) { if (this.loop) {
this.frameIndex = 0; this.frameIndex = 0;
...@@ -1127,21 +918,16 @@ export class MyAnimation extends MySprite { ...@@ -1127,21 +918,16 @@ export class MyAnimation extends MySprite {
this.restartFlag = false; this.restartFlag = false;
this.frameIndex = 0; this.frameIndex = 0;
} else { } else {
this.frameIndex -- ; this.frameIndex--;
this.playEnd(); this.playEnd();
return; return;
} }
} }
this.frameArr[this.frameIndex].visible = true; this.frameArr[this.frameIndex].visible = true;
} }
_updateDelay(delay) { _updateDelay(delay) {
this.curDelay += delay; this.curDelay += delay;
if (this.curDelay < this.delayPerUnit) { if (this.curDelay < this.delayPerUnit) {
return; return;
...@@ -1151,7 +937,9 @@ export class MyAnimation extends MySprite { ...@@ -1151,7 +937,9 @@ export class MyAnimation extends MySprite {
} }
_updateLastDate() { _updateLastDate() {
if (!this.playFlag) { return; } if (!this.playFlag) {
return;
}
let delay = 0; let delay = 0;
if (this.lastDateTime) { if (this.lastDateTime) {
...@@ -1165,18 +953,18 @@ export class MyAnimation extends MySprite { ...@@ -1165,18 +953,18 @@ export class MyAnimation extends MySprite {
super.update($event); super.update($event);
this._updateLastDate(); this._updateLastDate();
} }
} }
// --------=========== util func =============------------- // --------=========== util func =============-------------
export function tweenChange(
export function tweenChange(item, obj, time = 0.8, callBack = null, easing = null, update = null) { item,
obj,
time = 0.8,
callBack = null,
easing = null,
update = null
) {
const tween = new TWEEN.Tween(item).to(obj, time * 1000); const tween = new TWEEN.Tween(item).to(obj, time * 1000);
if (callBack) { if (callBack) {
...@@ -1188,7 +976,7 @@ export function tweenChange(item, obj, time = 0.8, callBack = null, easing = nul ...@@ -1188,7 +976,7 @@ export function tweenChange(item, obj, time = 0.8, callBack = null, easing = nul
tween.easing(easing); tween.easing(easing);
} }
if (update) { if (update) {
tween.onUpdate( (a, b) => { tween.onUpdate((a, b) => {
update(a, b); update(a, b);
}); });
} }
...@@ -1197,11 +985,13 @@ export function tweenChange(item, obj, time = 0.8, callBack = null, easing = nul ...@@ -1197,11 +985,13 @@ export function tweenChange(item, obj, time = 0.8, callBack = null, easing = nul
return tween; return tween;
} }
export function rotateItem(
item,
rotation,
export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = null) { time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000); const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000);
if (callBack) { if (callBack) {
...@@ -1216,11 +1006,17 @@ export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = ...@@ -1216,11 +1006,17 @@ export function rotateItem(item, rotation, time = 0.8, callBack = null, easing =
tween.start(); tween.start();
} }
export function scaleItem(
item,
export function scaleItem(item, scale, time = 0.8, callBack = null, easing = null) { scale,
time = 0.8,
const tween = new TWEEN.Tween(item).to({ scaleX: scale, scaleY: scale}, time * 1000); callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to(
{ scaleX: scale, scaleY: scale },
time * 1000
);
if (callBack) { if (callBack) {
tween.onComplete(() => { tween.onComplete(() => {
...@@ -1235,10 +1031,15 @@ export function scaleItem(item, scale, time = 0.8, callBack = null, easing = nul ...@@ -1235,10 +1031,15 @@ export function scaleItem(item, scale, time = 0.8, callBack = null, easing = nul
return tween; return tween;
} }
export function moveItem(
export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) { item,
x,
const tween = new TWEEN.Tween(item).to({ x, y}, time * 1000); y,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item).to({ x, y }, time * 1000);
if (callBack) { if (callBack) {
tween.onComplete(() => { tween.onComplete(() => {
...@@ -1254,36 +1055,26 @@ export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) ...@@ -1254,36 +1055,26 @@ export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null)
return tween; return tween;
} }
export function endShow(item, s = 1) { export function endShow(item, s = 1) {
item.scaleX = item.scaleY = 0; item.scaleX = item.scaleY = 0;
item.alpha = 0; item.alpha = 0;
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({ alpha: 1, scaleX: s, scaleY: s }, 800) .to({ alpha: 1, scaleX: s, scaleY: s }, 800)
.easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth. .easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function() {})
})
.start(); .start();
} }
export function hideItem(item, time = 0.8, callBack = null, easing = null) { export function hideItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha == 0) {
if (item.alpha === 0) {
return; return;
} }
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha: 0}, time * 1000) .to({ alpha: 0 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function() {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1296,10 +1087,8 @@ export function hideItem(item, time = 0.8, callBack = null, easing = null) { ...@@ -1296,10 +1087,8 @@ export function hideItem(item, time = 0.8, callBack = null, easing = null) {
tween.start(); tween.start();
} }
export function showItem(item, time = 0.8, callBack = null, easing = null) { export function showItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha == 1) {
if (item.alpha === 1) {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1308,9 +1097,9 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) { ...@@ -1308,9 +1097,9 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) {
item.visible = true; item.visible = true;
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha: 1}, time * 1000) .to({ alpha: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function() {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1323,14 +1112,17 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) { ...@@ -1323,14 +1112,17 @@ export function showItem(item, time = 0.8, callBack = null, easing = null) {
tween.start(); tween.start();
} }
export function alphaItem(
export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = null) { item,
alpha,
time = 0.8,
callBack = null,
easing = null
) {
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha}, time * 1000) .to({ alpha: alpha }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function() {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1343,14 +1135,11 @@ export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = nul ...@@ -1343,14 +1135,11 @@ export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = nul
tween.start(); tween.start();
} }
export function showStar(item, time = 0.8, callBack = null, easing = null) { export function showStar(item, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item) const tween = new TWEEN.Tween(item)
.to({alpha: 1, scale: 1}, time * 1000) .to({ alpha: 1, scale: 1 }, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth. // .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(() => { .onComplete(function() {
if (callBack) { if (callBack) {
callBack(); callBack();
} }
...@@ -1363,97 +1152,103 @@ export function showStar(item, time = 0.8, callBack = null, easing = null) { ...@@ -1363,97 +1152,103 @@ export function showStar(item, time = 0.8, callBack = null, easing = null) {
tween.start(); tween.start();
} }
export function randomSortByArr(arr) { export function randomSortByArr(arr) {
const newArr = []; const newArr = [];
const tmpArr = arr.concat(); const tmpArr = arr.concat();
while (tmpArr.length > 0) { while (tmpArr.length > 0) {
const randomIndex = Math.floor( tmpArr.length * Math.random() ); const randomIndex = Math.floor(tmpArr.length * Math.random());
newArr.push(tmpArr[randomIndex]); newArr.push(tmpArr[randomIndex]);
tmpArr.splice(randomIndex, 1); tmpArr.splice(randomIndex, 1);
} }
return newArr; return newArr;
} }
export function radianToAngle(radian) { export function radianToAngle(radian) {
return radian * 180 / Math.PI; return (radian * 180) / Math.PI;
// 角度 = 弧度 * 180 / Math.PI; // 角度 = 弧度 * 180 / Math.PI;
} }
export function angleToRadian(angle) { export function angleToRadian(angle) {
return angle * Math.PI / 180; return (angle * Math.PI) / 180;
// 弧度= 角度 * Math.PI / 180; // 弧度= 角度 * Math.PI / 180;
} }
export function getPosByAngle(angle, len) { export function getPosByAngle(angle, len) {
const radian = (angle * Math.PI) / 180;
const radian = angle * Math.PI / 180;
const x = Math.sin(radian) * len; const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len; const y = Math.cos(radian) * len;
return {x, y}; return { x, y };
} }
export function getAngleByPos(px, py, mx, my) { export function getAngleByPos(px, py, mx, my) {
const x = Math.abs(px - mx); const x = Math.abs(px - mx);
const y = Math.abs(py - my); const y = Math.abs(py - my);
const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
const cos = y / z; const cos = y / z;
const radina = Math.acos(cos); // 用反三角函数求弧度 const radina = Math.acos(cos); // 用反三角函数求弧度
let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度 let angle = Math.floor((180 / (Math.PI / radina)) * 100) / 100; // 将弧度转换成角度
if (mx > px && my > py) {// 鼠标在第四象限 if (mx > px && my > py) {
// 鼠标在第四象限
angle = 180 - angle; angle = 180 - angle;
} }
if (mx === px && my > py) {// 鼠标在y轴负方向上 if (mx === px && my > py) {
// 鼠标在y轴负方向上
angle = 180; angle = 180;
} }
if (mx > px && my === py) {// 鼠标在x轴正方向上 if (mx > px && my === py) {
// 鼠标在x轴正方向上
angle = 90; angle = 90;
} }
if (mx < px && my > py) {// 鼠标在第三象限 if (mx < px && my > py) {
// 鼠标在第三象限
angle = 180 + angle; angle = 180 + angle;
} }
if (mx < px && my === py) {// 鼠标在x轴负方向 if (mx < px && my === py) {
// 鼠标在x轴负方向
angle = 270; angle = 270;
} }
if (mx < px && my < py) {// 鼠标在第二象限 if (mx < px && my < py) {
// 鼠标在第二象限
angle = 360 - angle; angle = 360 - angle;
} }
// console.log('angle: ', angle); // console.log('angle: ', angle);
return angle; return angle;
} }
export function removeItemFromArr(arr, item) { export function removeItemFromArr(arr, item) {
const index = arr.indexOf(item); const index = arr.indexOf(item);
if (index !== -1) { if (index != -1) {
arr.splice(index, 1); arr.splice(index, 1);
} }
} }
export function circleMove(
item,
x0,
y0,
time = 2,
export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = 1, callBack = null, easing = null) { addR = 360,
xPer = 1,
yPer = 1,
callBack = null,
easing = null
) {
const r = getPosDistance(item.x, item.y, x0, y0); const r = getPosDistance(item.x, item.y, x0, y0);
let a = getAngleByPos(item.x, item.y, x0, y0); let a = getAngleByPos(item.x, item.y, x0, y0);
a += 90; a += 90;
const obj = {r, a}; const obj = { r, a };
item._circleAngle = a; item._circleAngle = a;
const targetA = a + addR; const targetA = a + addR;
const tween = new TWEEN.Tween(item).to({_circleAngle: targetA}, time * 1000); const tween = new TWEEN.Tween(item).to(
{ _circleAngle: targetA },
time * 1000
);
if (callBack) { if (callBack) {
tween.onComplete(() => { tween.onComplete(() => {
...@@ -1464,14 +1259,13 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = ...@@ -1464,14 +1259,13 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer =
tween.easing(easing); tween.easing(easing);
} }
tween.onUpdate( (item, progress) => { tween.onUpdate((item, progress) => {
// console.log(item._circleAngle); // console.log(item._circleAngle);
const r = obj.r; const r = obj.r;
const a = item._circleAngle; const a = item._circleAngle;
const x = x0 + r * xPer * Math.cos(a * Math.PI / 180); const x = x0 + r * xPer * Math.cos((a * Math.PI) / 180);
const y = y0 + r * yPer * Math.sin(a * Math.PI / 180); const y = y0 + r * yPer * Math.sin((a * Math.PI) / 180);
item.x = x; item.x = x;
item.y = y; item.y = y;
...@@ -1482,12 +1276,10 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = ...@@ -1482,12 +1276,10 @@ export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer =
tween.start(); tween.start();
} }
export function getPosDistance(sx, sy, ex, ey) { export function getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx; const _x = ex - sx;
const _y = ey - sy; const _y = ey - sy;
const len = Math.sqrt( Math.pow(_x, 2) + Math.pow(_y, 2) ); const len = Math.sqrt(Math.pow(_x, 2) + Math.pow(_y, 2));
return len; return len;
} }
...@@ -1502,29 +1294,6 @@ export function delayCall(callback, second) { ...@@ -1502,29 +1294,6 @@ export function delayCall(callback, second) {
.start(); .start();
} }
export function formatTime(fmt, date) {
// "yyyy-MM-dd HH:mm:ss";
const o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); }
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1)
? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return fmt;
}
export function getMinScale(item, maxLen) { export function getMinScale(item, maxLen) {
const sx = maxLen / item.width; const sx = maxLen / item.width;
const sy = maxLen / item.height; const sy = maxLen / item.height;
...@@ -1532,11 +1301,7 @@ export function getMinScale(item, maxLen) { ...@@ -1532,11 +1301,7 @@ export function getMinScale(item, maxLen) {
return minS; return minS;
} }
export function jelly(item, time = 0.7) { export function jelly(item, time = 0.7) {
if (item.jellyTween) { if (item.jellyTween) {
TWEEN.remove(item.jellyTween); TWEEN.remove(item.jellyTween);
} }
...@@ -1552,10 +1317,16 @@ export function jelly(item, time = 0.7) { ...@@ -1552,10 +1317,16 @@ export function jelly(item, time = 0.7) {
return; return;
} }
const data = arr[index]; const data = arr[index];
const t = tweenChange(item, {scaleX: data[0], scaleY: data[1]}, data[2], () => { const t = tweenChange(
index ++; item,
{ scaleX: data[0], scaleY: data[1] },
data[2],
() => {
index++;
run(); run();
}, TWEEN.Easing.Sinusoidal.InOut); },
TWEEN.Easing.Sinusoidal.InOut
);
item.jellyTween = t; item.jellyTween = t;
}; };
...@@ -1564,20 +1335,24 @@ export function jelly(item, time = 0.7) { ...@@ -1564,20 +1335,24 @@ export function jelly(item, time = 0.7) {
[baseSX * 0.98, baseSY * 1.02, t * 2], [baseSX * 0.98, baseSY * 1.02, t * 2],
[baseSX * 1.02, baseSY * 0.98, t * 2], [baseSX * 1.02, baseSY * 0.98, t * 2],
[baseSX * 0.99, baseSY * 1.01, t * 2], [baseSX * 0.99, baseSY * 1.01, t * 2],
[baseSX * 1.0, baseSY * 1.0, t * 2], [baseSX * 1.0, baseSY * 1.0, t * 2]
]; ];
run(); run();
} }
/**
* 烟花爆炸效果动画
export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen = 80, showTime = 0.4) { * @param img 颗粒的图片
* @param pos 爆点的坐标
* @param parent 必须传一个父类
for (let i = 0; i < num; i ++) { */
export function showPopParticle(img, pos, parent) {
const num = 20;
const maxLen = 100;
const minLen = 40;
for (let i = 0; i < num; i++) {
const particle = new MySprite(); const particle = new MySprite();
particle.init(img); particle.init(img);
particle.x = pos.x; particle.x = pos.x;
...@@ -1587,8 +1362,8 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen ...@@ -1587,8 +1362,8 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen
const randomR = 360 * Math.random(); const randomR = 360 * Math.random();
particle.rotation = randomR; particle.rotation = randomR;
const randomS = 0.3 + Math.random() * 0.7; const randomS = 0.5 + Math.random() * 0.5;
particle.setScaleXY(randomS * 0.3); particle.setScaleXY(randomS);
const randomX = Math.random() * 20 - 10; const randomX = Math.random() * 20 - 10;
particle.x += randomX; particle.x += randomX;
...@@ -1596,39 +1371,23 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen ...@@ -1596,39 +1371,23 @@ export function showPopParticle(img, pos, parent, num = 20, minLen = 40, maxLen
const randomY = Math.random() * 20 - 10; const randomY = Math.random() * 20 - 10;
particle.y += randomY; particle.y += randomY;
const randomL = minLen + Math.random() * (maxLen - minLen); const randomL = minLen + Math.random() * maxLen;
const randomA = 360 * Math.random(); const randomA = 360 * Math.random();
const randomT = getPosByAngle(randomA, randomL); const randomT = getPosByAngle(randomA, randomL);
moveItem(particle, particle.x + randomT.x, particle.y + randomT.y, showTime, () => { moveItem(
particle,
particle.x + randomT.x,
particle.y + randomT.y,
}, TWEEN.Easing.Exponential.Out); 0.4,
() => {},
// scaleItem(particle, 0, 0.6, () => { TWEEN.Easing.Exponential.Out
// );
// });
scaleItem(particle, randomS, 0.6, () => {
}, TWEEN.Easing.Exponential.Out);
setTimeout(() => {
hideItem(particle, 0.4, () => {
}, TWEEN.Easing.Cubic.In);
}, showTime * 0.5 * 1000);
scaleItem(particle, 0, 0.6, () => {});
} }
} }
export function shake(item, time = 0.5, callback = null, rate = 1) { export function shake(item, time = 0.5, callback = null, rate = 1) {
if (item.shakeTween) { if (item.shakeTween) {
return; return;
} }
...@@ -1640,37 +1399,62 @@ export function shake(item, time = 0.5, callback = null, rate = 1) { ...@@ -1640,37 +1399,62 @@ export function shake(item, time = 0.5, callback = null, rate = 1) {
const baseY = item.y; const baseY = item.y;
const easing = TWEEN.Easing.Sinusoidal.InOut; const easing = TWEEN.Easing.Sinusoidal.InOut;
const move4 = () => { const move4 = () => {
moveItem(item, baseX, baseY, time / 4, () => { moveItem(
item,
baseX,
baseY,
time / 4,
() => {
item.shakeTween = false; item.shakeTween = false;
if (callback) { if (callback) {
callback(); callback();
} }
}, easing); },
easing
);
}; };
const move3 = () => { const move3 = () => {
moveItem(item, baseX + offX / 4, baseY + offY / 4, time / 4, () => { moveItem(
item,
baseX + offX / 4,
baseY + offY / 4,
time / 4,
() => {
move4(); move4();
}, easing); },
easing
);
}; };
const move2 = () => { 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(); move3();
}, easing); },
easing
);
}; };
const move1 = () => { const move1 = () => {
moveItem(item, baseX + offX, baseY + offY, time / 7.5, () => { moveItem(
item,
baseX + offX,
baseY + offY,
time / 8,
() => {
move2(); move2();
}, easing); },
easing
);
}; };
move1(); move1();
} }
// --------------- custom class -------------------- // --------------- custom class --------------------
.game-container {
width: 100%;
height: 100%;
background: #ffffff;
background-size: cover;
}
#canvas {
}
@font-face
{
font-family: 'BRLNSDB';
src: url("../../assets/font/BRLNSDB.TTF") ;
}
.game-container {
width: 100%;
height: 100%;
//background-image: url("/assets/listen-read-circle/bg.jpg");
background: #ffffff;
background-repeat: no-repeat;
background-size: cover;
}
.read-and-point-copy {
width: 500px;
height: 85px;
object-fit: contain;
text-shadow: 0 6px 4px rgba(0, 0, 0, 0.5), 0 3px 0 #fffecc;
font-family: Questrian;
font-size: 72px;
font-weight: normal;
font-stretch: normal;
font-style: normal;
line-height: normal;
letter-spacing: normal;
color: #f8e424;
}
.read-and-point-copy .text-style-1 {
font-size: 48px;
}
.read-and-point-copy .text-style-2 {
font-size: 64px;
}
@font-face
{
font-family: 'BRLNSDB';
src: url("../../assets/font/BRLNSDB.TTF") ;
}
@font-face
{
font-family: 'RoundedBold';
src: url("../../assets/font/ArialRoundedBold.otf") ;
}
@font-face{
font-family: 'BRLNSB_1';
src: url("../../assets/font/BerlinSansFB/BRLNSB_1.TTF") ;
}
@font-face{
font-family: 'BerlinSansFBDemi-Bold';
src: url("../../assets/font/BerlinSansFB/BRLNSDB_1.TTF") ;
}
@font-face{
font-family: 'BRLNSR_1';
src: url("../../assets/font/BerlinSansFB/BRLNSR_1.TTF") ;
}
@font-face{
font-family: 'GOTHIC_1';
src: url("../../assets/font/CenturyGothic/GOTHIC_1.TTF") ;
}
@font-face{
font-family: 'GOTHICB_1';
src: url("../../assets/font/CenturyGothic/GOTHICB_1.TTF") ;
}
@font-face{
font-family: 'GOTHICBI_1';
src: url("../../assets/font/CenturyGothic/GOTHICBI_1.TTF") ;
}
@font-face{
font-family: 'GOTHICI_1';
src: url("../../assets/font/CenturyGothic/GOTHICI_1.TTF") ;
}
@font-face{
font-family: 'MMTextBook';
src: url("../../assets/font/MMTextBook/MMTextBook.otf") ;
}
@font-face{
font-family: 'MMTextBook-Bold';
src: url("../../assets/font/MMTextBook/MMTextBook-Bold.otf") ;
}
@font-face{
font-family: 'MMTextBook-BoldItalic';
src: url("../../assets/font/MMTextBook/MMTextBook-BoldItalic.otf") ;
}
@font-face{
font-family: 'MMTextBook-Italic';
src: url("../../assets/font/MMTextBook/MMTextBook-Italic.otf") ;
}
import {Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener} from '@angular/core'; import {
Component,
ElementRef,
ViewChild,
OnInit,
Input,
OnDestroy,
HostListener
} from "@angular/core";
import {
MySprite,
getMinScale,
ShapeRect,
ShapeCircle,
tweenChange,
randomSortByArr,
Label,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem,
hideItem,
showItem,
ShapeRectNew
} from "./Unit";
import { localImages, localAudios } from "./resources";
import { Cartoon } from './Cartoon'
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import * as _ from "lodash";
import TWEEN from "@tweenjs/tween.js";
const defauleFormData = {
dataArray:[
{
time: 15,
question:{
text:"This is Demo, please set question in form page",
image_url:"question-image",
audio_url:""
},
choice:{
correct:{ isText: true, text: "Correct choice", image_url: "bg-240-180" },
incorrect:[
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
]
}
},
{
time: 15,
question:{
text:"This is Demo, please set question in form page",
image_url:"",
audio_url:"sm-display"
},
choice:{
correct:{ isText: true, text: "Correct choice", image_url: "bg-240-180" },
incorrect:[
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
]
}
},
{
time: 15,
question:{
text:"",
image_url:"question-image",
audio_url:"sm-display"
},
choice:{
correct:{ isText: true, text: "Correct choice", image_url: "bg-240-180" },
incorrect:[
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
]
}
},
{
time: 15,
question:{
text:"This is Demo, please set question in form page",
image_url:"",
audio_url:""
},
choice:{
correct:{ isText: true, text: "Correct choice", image_url: "bg-240-180" },
incorrect:[
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
{ isText: true, text: "Incorrect choice", image_url: "bg-240-180" },
]
}
}
]
}
@Component({
selector: "app-play",
templateUrl: "./play.component.html",
styleUrls: ["./play.component.scss"]
})
export class PlayComponent implements OnInit, OnDestroy {
g_cartoon = new Cartoon()
// ------------ 全局数据 ------------
g_stage; //中心舞台
g_enableTouch = true; // 触摸使能
g_canvasLeft;
g_canvasTop;
g_animationId: any;
g_mapScale = 1; // 缩放比例
g_KEY = "DataKey_MultipleChoice";
g_canvasWidth = 1280;
g_canvasHeight = 720;
g_canvasBaseW = 1280;
g_canvasBaseH = 720;
g_winResizeEventStream = new Subject();
g_clickX; // 点击坐标 X
g_clickY; // 点击坐标 Y
g_ctx; // canvas 实例
g_data; // 数据
g_formData; // 核心表单数据
g_teacherFlag = false; // 默认角色
g_currentUser;
// ------------------------------------
// ------------ 私有数据 ------------
m_clickQueue = {} //点击事件处理队列
m_endPageArr;
m_showPetalFlag;
m_elementPetalArr;
m_showElementPetalFlag;
m_PetalImage = "petal_" // 飘落动画
m_renderArr // 渲染队列
m_currentQuestion = 0;
m_totalQuestion = 0;
m_isGameEnd = true;
m_correctNumber = 0;
m_totalTime = 0;
m_autoPlay;
// ------------------------------------
// ------------ 消息 ------------
m_Message_Start = "message_start"
m_Message_Complete = "message_complete"
m_Message_NextQuestion = "message_nextQuestion"
// ------------------------------------
// ------------ 调试变量 ------------
g_EnableStageRuler = false; // 使能舞台背景格尺
g_ForceChangeDefaultRole = false // 强制当前角色为默认角色
g_EnableTestSendEvent = false // 强制当前角色为默认角色
// ------------------------------------
g_serverAllUser;
g_startBtn;
// 当数据加载完毕后,执行
systemReady(){
this.initGame()
}
// 屏幕尺寸变化后执行
handleScreenResize(){
// this.initSystem();
// this.restartGame()
}
restartGame() {
this.g_cartoon.getCartoonElement("timer").stop()
this.g_cartoon.stopAllAudio()
this.stopEndPatal()
this.initGame()
}
// ------------------------------------------------------------------------------
// 游戏核心处理区
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// initGame 初始化游戏
// startGame_Student 在收到开始信息后开始执行
// startGame_Teacher 教师点击开始按钮后执行
// startAnswer 开始答题
// endAnswer 结束答题
// showRankingList 显示排行榜
// initTestEvent 用于在测试时模拟发送消息
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
initGame(){
this.stopEndPatal();
if(!this.g_EnableStageRuler){
this.initBackground()
}
this.m_currentQuestion = 0;
this.m_totalQuestion = 0;
this.m_isGameEnd = true;
this.m_correctNumber = 0;
this.m_totalTime = 0;
this.initStartPage();
this.initAnswer();
this.initReadyGoBackground();
this.initReadyGoContainer();
this.initRankingList();
this.g_cartoon.getCartoonElement("timer").subscribeTimeup(()=>{
this.handleTimeup()
});
if(this.g_EnableTestSendEvent){
this.initTestEvent()
}
this.syncServerPage();
}
syncServerPage() {
const allUser = this.g_serverAllUser;
if (allUser) {
console.log('allUser: ', allUser);
for (let i = 0; i < allUser.length; i++) {
const userData = allUser[i];
if (userData.user.classRole == 'tea') {
if (userData.aspect) {
const aspect = JSON.parse( JSON.parse(userData.aspect) );
console.log('aspect: ', aspect);
if (aspect.startFlag) {
if (this.g_teacherFlag) {
this.g_cartoon.playAudio("sm-choice-in")
this.startGame_Teacher();
// this.sendServerEvent(this.m_Message_Start, {startFlag: true})
// this.g_startBtn.hide(()=>{
// this.g_enableTouch = true;
// })
// setTimeout(() => {
// this.g_enableTouch = true;
// }, 2000);
this.g_startBtn.alpha = 0;
this.g_enableTouch = true;
this.fillTeacherPageData();
} else {
this.startGame_Student();
this.g_enableTouch = true;
}
}
}
break;
}
}
}
}
fillTeacherPageData() {
const allUser = this.g_serverAllUser;
if (allUser) {
// console.log('allUser 2 : ', allUser);
for (let i = 0; i < allUser.length; i++) {
const userData = allUser[i];
if (userData.user.classRole == 'stu') {
if (userData.aspect) {
const aspect = JSON.parse( JSON.parse(userData.aspect) );
this.g_cartoon.getCartoonElement("Teacher_RankList").handleGetData(aspect);
// console.log('aspect: ', aspect);
// this.addTeacherPageData(aspect);
}
break;
}
}
}
}
startGame_Student(){
this.g_cartoon.playAudio("sm-choice-in")
this.g_cartoon.getCartoonElement("cover").hide()
this.startAnimation(()=>{
this.startAnswer();
})
}
startGame_Teacher(){
this.initTeacherPage()
this.startAnimation(()=>{
this.g_cartoon.getCartoonElement("Teacher_RankList").in()
})
}
startAnimation(callback?){
this.g_cartoon.getCartoonElement("title").out()
this.g_cartoon.getCartoonElement("group").out()
callback && setTimeout(()=>{
callback()
},600)
}
startAnswer(){
this.g_cartoon.getCartoonElement("question-container").in()
this.g_cartoon.getCartoonElement("question-container").setContent("image", "question-image")
this.g_cartoon.getCartoonElement("drop-down").in()
this.g_cartoon.getCartoonElement("timer").in()
this.nextQuestion(false)
this.g_cartoon.getCartoonElement("ready-go-container").in(()=>{
this.goQuestion();
})
}
endAnswer(callback?){
callback && setTimeout(()=>{
callback()
},100)
}
showRankingList(){
this.g_cartoon.getCartoonElement("ranking-list").setList({},0)
this.g_cartoon.getCartoonElement("ranking-list").setList({},1)
this.g_cartoon.getCartoonElement("ranking-list").setList({},2)
this.g_cartoon.getCartoonElement("ranking-list").setList({},3)
this.g_cartoon.getCartoonElement("ranking-list").setMeIcon(2)
this.g_cartoon.playAudio("sm-choice-complete")
this.g_cartoon.getCartoonElement("ranking-list").in()
this.showEndPatal();
}
loadQuestion(){
let max = this.g_formData.dataArray.length;
if(this.m_currentQuestion == max){
return {
currentIndex:this.m_currentQuestion,
totalIndex:max,
theEnd:true
}
}
let time = this.g_formData.dataArray[this.m_currentQuestion].time?this.g_formData.dataArray[this.m_currentQuestion].time:1
let questionText = this.g_formData.dataArray[this.m_currentQuestion].question.text;
let questionImage = this.g_formData.dataArray[this.m_currentQuestion].question.image_url;
let questionAudio = this.g_formData.dataArray[this.m_currentQuestion].question.audio_url;
let choiceCard = []
choiceCard.push({
answer: true,
isText: this.g_formData.dataArray[this.m_currentQuestion].choice.correct.isText,
text: this.g_formData.dataArray[this.m_currentQuestion].choice.correct.text,
image_url: this.g_formData.dataArray[this.m_currentQuestion].choice.correct.image_url
})
this.g_formData.dataArray[this.m_currentQuestion].choice.incorrect.forEach(item => {
choiceCard.push({
answer: false,
isEmpty: false,
isText: item.isText,
text: item.text,
image_url: item.image_url
})
});
choiceCard = this.randomArray_shuffle(choiceCard)
// cc
let mainContent = {}
let dropDownContent ={}
if( questionText !== "" && questionImage ==="" && questionAudio===""){
// 文字
mainContent = {
type: "text",
key: questionText
};
}else if(questionText === "" && questionImage !=="" && questionAudio===""){
// 图片
mainContent = {
type: "image",
key: questionImage
};
}else if(questionText === "" && questionImage ==="" && questionAudio!==""){
// 音频
mainContent = {
type: "audio",
key: questionAudio
};
}else if( questionText !== "" && questionImage !=="" && questionAudio===""){
// 文字 图片
mainContent = {
type: "text",
key: questionText
};
dropDownContent = {
type: "image",
key: questionImage
};
}else if(questionText !== "" && questionImage ==="" && questionAudio!==""){
// 文字 音频
mainContent = {
type: "text",
key: questionText
};
dropDownContent = {
type: "audio",
key: questionAudio
};
}else if(questionText === "" && questionImage !=="" && questionAudio!==""){
// 图片 音频
mainContent = {
type: "audio",
key: questionAudio
};
dropDownContent = {
type: "image",
key: questionImage
};
}else if(questionText !== "" && questionImage !=="" && questionAudio!==""){
// 文字 图片 音频
mainContent = {
type: "text",
key: questionText,
additionalAudio: questionAudio
};
dropDownContent = {
type: "image",
key: questionImage
};
}
this.m_currentQuestion++;
return {
currentIndex:this.m_currentQuestion,
totalIndex:max,
time: time,
theEnd:false,
mainContent: mainContent,
dropDownContent: dropDownContent,
questionText:questionText,
questionImage: questionImage,
questionAudio: questionAudio,
choiceCards: choiceCard
}
}
setQuestion(showData, startNow:boolean= true){
if(showData.theEnd){
return false;
}
if(showData.mainContent.type){
this.g_cartoon.getCartoonElement("question-container").setContent(showData.mainContent.type, showData.mainContent.key)
}
if(showData.mainContent.additionalAudio){
this.g_cartoon.getCartoonElement( "additional-speaker").setAduio(showData.mainContent.additionalAudio)
this.g_cartoon.getCartoonElement( "additional-speaker").show()
}else{
this.g_cartoon.getCartoonElement( "additional-speaker").hidden()
}
if(showData.dropDownContent.type){
this.g_cartoon.getCartoonElement("drop-down").setContent(showData.dropDownContent.type, showData.dropDownContent.key)
if(showData.mainContent.additionalAudio){
this.g_cartoon.getCartoonElement("drop-down").down_type2()
this.g_cartoon.getCartoonElement("question-container").contentDown_type2()
}else{
this.g_cartoon.getCartoonElement("drop-down").down()
this.g_cartoon.getCartoonElement("question-container").contentDown()
}
}else{
this.g_cartoon.getCartoonElement("drop-down").up()
this.g_cartoon.getCartoonElement("question-container").contentUp()
}
this.g_cartoon.getCartoonElement("drop-down").setTitleNumber(showData.currentIndex, showData.totalIndex)
this.g_cartoon.getCartoonElement( "ChoiceCard1").out()
this.g_cartoon.getCartoonElement( "ChoiceCard2").out()
this.g_cartoon.getCartoonElement( "ChoiceCard3").out()
this.g_cartoon.getCartoonElement( "ChoiceCard4").out()
showData.choiceCards.forEach((item,index)=>{
let i = index + 1
this.g_cartoon.getCartoonElement( "ChoiceCard" + i ).in()
this.g_cartoon.getCartoonElement( "ChoiceCard" + i ).setChoice(item)
})
this.g_cartoon.getCartoonElement("timer").reset(showData.time);
if(startNow){
this.goQuestion();
}
this.g_enableTouch = true;
return true
}
goQuestion(){
setTimeout(()=>{
this.g_enableTouch = true;
this.autoPlayQuestionAudio()
this.g_cartoon.getCartoonElement("timer").run()
},100)
}
autoPlayQuestionAudio(){
this.m_autoPlay && this.m_autoPlay()
this.m_autoPlay = null;
}
setAutoPlayQuestionAudio(f:Function){
this.m_autoPlay = f
}
nextQuestion(startNow:boolean = true){
let showData = this.loadQuestion()
let score_data = {
user: this.g_currentUser,
correctNumber: this.m_correctNumber,
totalNumber: showData.totalIndex,
isComplete: showData.theEnd,
totalTime: this.m_totalTime
}
this.sendServerEvent(this.m_Message_NextQuestion, score_data)
return this.setQuestion(showData, startNow)
}
handleClickChoice( targetId, isCorrectAnswer){
this.g_cartoon.stopAllAudio()
let waitingTime = 3000;
let totalID = ["ChoiceCard1","ChoiceCard2","ChoiceCard3","ChoiceCard4"]
this.g_cartoon.getCartoonElement("timer").stop()
this.g_cartoon.stopAudio()
if(isCorrectAnswer){ //选择正确
this.m_correctNumber++;
this.g_cartoon.playAudio("sm-choice-correct")
this.showJellyAnimation(targetId)
this.g_cartoon.getCartoonElement(targetId).correct()
let index = totalID.indexOf(targetId);
totalID.splice(index, 1)
totalID.forEach((item)=>{
this.g_cartoon.getCartoonElement(item).normal()
})
}else{ //选择错误
this.g_cartoon.playAudio("sm-choice-incorrect")
this.showShakeAnimation(targetId)
this.g_cartoon.getCartoonElement(targetId).error()
let index = totalID.indexOf(targetId);
totalID.splice(index, 1)
totalID.forEach((item)=>{
this.g_cartoon.getCartoonElement(item).showAnswer()
})
}
setTimeout(()=>{
if(!this.nextQuestion()){
this.endAnswer(()=>{
this.g_cartoon.playAudio("sm-choice-complete")
this.showEndPatal();
// this.showRankingList()
})
}else{
let totalID = ["ChoiceCard1","ChoiceCard2","ChoiceCard3","ChoiceCard4"]
totalID.forEach((item)=>{
this.g_cartoon.getCartoonElement(item).ready()
})
}
}, waitingTime)
}
handleTimeup(){
this.g_cartoon.stopAllAudio()
let waitingTime = 3000;
this.g_enableTouch = false;
this.g_cartoon.playAudio("sm-choice-timeup-0")
let totalID = ["ChoiceCard1","ChoiceCard2","ChoiceCard3","ChoiceCard4"]
this.g_cartoon.getCartoonElement("timer").stop()
totalID.forEach((item)=>{
this.g_cartoon.getCartoonElement(item).showAnswer()
})
setTimeout(()=>{
if(!this.nextQuestion()){
this.endAnswer(()=>{
this.g_cartoon.playAudio("sm-choice-complete")
this.showEndPatal();
// this.showRankingList()
})
}else{
let totalID = ["ChoiceCard1","ChoiceCard2","ChoiceCard3","ChoiceCard4"]
totalID.forEach((item)=>{
this.g_cartoon.getCartoonElement(item).ready()
})
this.g_enableTouch = true;
}
}, waitingTime)
}
initTestEvent(){
if(this.g_ForceChangeDefaultRole){
if(this.g_teacherFlag){
// let totalTime = 0;
// let correct = 0;
let randomUser = []
for(let i=0; i<18; i++){
randomUser.push({
uuid: Math.floor(1000*Math.random()),
nick_name: "Stu_" + i
})
}
setTimeout(() => {
setInterval(()=>{
let user = randomUser[Math.floor(18*Math.random())]
let score_data = {
user: randomUser[Math.floor(18*Math.random())],
correctNumber: Math.floor(100 * Math.random()),
totalNumber: 100,
isComplete: Math.floor(10 * Math.random())%2==1?true:false,
totalTime: Math.floor(100 * Math.random())
}
this.sendServerEvent(this.m_Message_NextQuestion, score_data)
},100)
}, 3000);
}else{
setTimeout(()=>{
this.sendServerEvent(this.m_Message_Start, {})
},1000)
}
}
}
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// 初始化 背景
// ------------------------------------------------------------------------------
initBackground(){
let element = this.g_cartoon.createCartoonElement("background", "MySprite",1280,720)
element.ref.init(this.g_cartoon.images.get("background"))
element.ref.x = this.g_canvasWidth / 2;
element.ref.y = this.g_canvasHeight /2;
element.ref.scaleX = this.g_canvasWidth / 1280
element.ref.scaleY = this.g_canvasHeight / 720
this.render(element.ref)
}
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// 初始化 开始页
// ------------------------------------------------------------------------------
initStartPage(){
this.initTitle()
this.initGroup();
if(this.g_teacherFlag){
this.initStartButton()
this.initTeacherListener()
}else{
this.initCover()
this.initStudentListener();
}
}
initStudentListener(){
this.addServerListener(this.m_Message_Start, (data)=>{
this.startGame_Student()
this.g_enableTouch = true;
})
}
initTeacherListener(){
this.addServerListener(this.m_Message_NextQuestion, (data)=>{
this.g_cartoon.getCartoonElement("Teacher_RankList").handleGetData(data)
this.g_enableTouch = true;
})
}
initTitle() {
let title = this.g_cartoon.createCartoonElement("title", "MySprite",494,82)
title.ref.init(this.g_cartoon.images.get("title"))
title.ref.x = this.g_cartoon.clientWidth/2
title.ref.y = (59+title.ref.height/2)*this.g_mapScale;
title.ref.setScaleXY(this.g_mapScale);
title.out = ()=>{
let moveDistance = this.g_cartoon.clientHeight - title.ref.height - 10
tweenChange(title.ref,{ x:title.ref.x, y: title.ref.y-moveDistance }, 1 )
}
this.render(title.ref)
}
initGroup() {
let group = this.g_cartoon.createCartoonElement("group", "MySprite",1158,226)
group.ref.init(this.g_cartoon.images.get("group"))
group.ref.x = this.g_cartoon.clientWidth/2;
group.ref.y = this.g_cartoon.clientHeight/2;
group.ref.setScaleXY(this.g_mapScale);
group.out = ()=>{
let moveDistance = this.g_cartoon.clientWidth + group.ref.width + 10
tweenChange(group.ref,{ x:group.ref.x - moveDistance, y:group.ref.y }, 0.5 )
}
this.render(group.ref)
}
initStartButton() {
let startBtn = this.g_cartoon.createCartoonElement("startBtn", "MySprite",340,140)
startBtn.ref.init(this.g_cartoon.images.get("startBtn"))
startBtn.ref.x = this.g_cartoon.getOrigin().x + (935 + startBtn.ref.width/2)*this.g_mapScale // this.g_cartoon.clientWidth/2;
startBtn.ref.y = this.g_cartoon.getOrigin().y + (564 + startBtn.ref.height/2)*this.g_mapScale
startBtn.ref.setScaleXY(this.g_mapScale);
startBtn.hide = (callback)=>{
tweenChange(startBtn.ref, { scaleX: this.g_mapScale * 1.5, scaleY: this.g_mapScale * 1.5 } , 0.2,()=>{
tweenChange(startBtn.ref, { scaleX: 0, scaleY: 0 } , 0.2, ()=>{
callback && callback()
} )
} )
}
this.g_startBtn = startBtn.ref;
this.subscribeClickEvent("startBtn",()=>{
this.g_cartoon.playAudio("sm-choice-in")
this.startGame_Teacher();
this.sendServerEvent(this.m_Message_Start, {startFlag: true})
startBtn.hide(()=>{
this.g_enableTouch = true;
})
setTimeout(() => {
this.g_enableTouch = true;
}, 2000);
})
this.render(startBtn.ref)
}
initCover() {
let shapeBg = this.g_cartoon.createCartoonElement("cover", "ShapeRectNew")
const lenW = 400 * this.g_mapScale;
shapeBg.ref.setSize(lenW, lenW / 3 * 1.5, 30 * this.g_mapScale);
shapeBg.ref.alpha = 0.5;
shapeBg.ref.fillColor = '#000000';
shapeBg.ref.x = this.g_canvasWidth/2 - shapeBg.ref.width / 2;
shapeBg.ref.y = this.g_canvasHeight/2 - shapeBg.ref.height / 2;
const label = new Label();
label.fontName = 'BRLNSDB';
label.fontColor = '#ffffff';
label.text = "ready .."
label.fontSize = 50 * this.g_mapScale;
label.textAlign = 'center';
label.x = shapeBg.ref.width / 2;
label.y = shapeBg.ref.height / 2;
shapeBg.ref.addChild(label);
shapeBg.hide = ()=>{
tweenChange(shapeBg.ref, { scaleX: 0, scaleY: 0 } , 0.1 )
}
// if (this.g_teacherFlag) {
// label.text = 'start';
// } else {
// label.text = 'ready ..';
// }
this.render(shapeBg.ref);
}
// ------------------------------------------------------------------------------
// End 初始化卡通元素
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// 初始化 排行榜
// ------------------------------------------------------------------------------
initTeacherPage() {
const w = 600;
const h = 500;
const lineW = 4 * this.g_mapScale;
let frame = this.g_cartoon.createCartoonElement("Teacher_RankList", "ShapeRectNew")
frame.ref.setSize(w, h, 20 * this.g_mapScale );
frame.ref.fill = false;
frame.ref.setOutLine('#ffffff', lineW);
frame.ref.setScaleXY(0);
frame.ref.x = this.g_canvasWidth / 2 - w * this.g_mapScale / 2;
frame.ref.y = this.g_canvasHeight / 2 - h * this.g_mapScale / 2// - 20 * this.g_mapScale;
const pageShowNum = 5;
const itemH = h - lineW;
const baseY = lineW / 2;
let listItemArray = []
for (let i = 0; i < pageShowNum; i ++) {
const listItem = new ShapeRect();
listItem.setSize( w * 0.96, itemH / pageShowNum * 1);
listItem.x = (w - listItem.width) / 2;
listItem.y = baseY + i * itemH / pageShowNum;
listItem.alpha = 0;
frame.ref.addChild(listItem);
const labelNum = new Label();
labelNum.textAlign = 'center';
labelNum.fontColor = '#ffffff';
labelNum.fontName = 'BRLNSDB';
labelNum.fontSize = 50;
labelNum.text = i.toString();
labelNum.x = 50;
labelNum.y = listItem.height / 2;
listItem.addChild(labelNum);
const labelName = new Label();
labelName.textAlign = 'center';
labelName.fontColor = '#ffffff';
labelName.fontSize = 40;
labelName.text = '张三';
labelName.x = 220;
labelName.y = listItem.height / 2;
listItem.addChild(labelName);
const labelScore = new Label();
labelScore.textAlign = 'center';
labelScore.fontColor = '#ffffff';
labelScore.fontSize = 35;
labelScore.text = Math.floor( Math.random() * 100 ).toString();
labelScore.x = 410;
labelScore.y = listItem.height / 2;
listItem.addChild(labelScore);
const labelFinish = new MySprite();
labelFinish.init(this.g_cartoon.images.get('t_right'));
labelFinish.setScaleXY(0.07);
labelFinish.x = listItem.width - 30;
labelFinish.y = listItem.height / 2;
listItem.addChild(labelFinish);
if (i != pageShowNum - 1) {
const line = new ShapeRect();
line.setSize(listItem.width, lineW);
line.fillColor = '#ffffff';
line.y = listItem.height;
listItem.addChild(line);
}
listItem['num'] = labelNum;
listItem['name'] = labelName;
listItem['score'] = labelScore;
listItem['finish'] = labelFinish;
labelNum.visible = false;
labelName.visible = false;
labelScore.visible = false;
labelFinish.visible = false;
listItemArray.push(listItem)
}
const pageLabel = this.g_cartoon.createCartoonElement("teacher-ranklist-page-nav", "Label")
pageLabel.ref.textAlign = 'center';
pageLabel.ref.fontColor = '#ffffff';
pageLabel.ref.fontName = 'BRLNSDB';
pageLabel.ref.fontSize = 40 // * this.g_mapScale;
pageLabel.ref.text = '1 / 1';
pageLabel.ref.x = this.g_canvasWidth / 2;
pageLabel.ref.y = this.g_canvasHeight/2 + (frame.ref.height /2 + 50)*this.g_mapScale;
pageLabel.ref.setScaleXY(0);
pageLabel.in = ()=>{
tweenChange(pageLabel.ref,{ scaleX: this.g_mapScale, scaleY: this.g_mapScale }, 0.1 )
}
pageLabel.out = ()=>{
tweenChange(pageLabel.ref,{ scaleX: 0, scaleY: 0 }, 0.1 )
}
this.render(pageLabel.ref)
let arrowL = this.g_cartoon.createCartoonElement("teacher-ranklist-left-btn", "MySprite")
arrowL.ref.init(this.g_cartoon.images.get('t_arrow'));
let arrowScale = this.g_mapScale * (50/arrowL.ref.width)
arrowL.ref.setScaleXY(0);
arrowL.ref.x = this.g_canvasWidth / 2 - 100*this.g_mapScale;
arrowL.ref.y = pageLabel.ref.y
arrowL.in = ()=>{
tweenChange(arrowL.ref,{ scaleX: arrowScale, scaleY: arrowScale }, 0.1 )
}
arrowL.out = ()=>{
tweenChange(arrowL.ref,{ scaleX: 0, scaleY: 0 }, 0.1 )
}
this.render(arrowL.ref);
const arrowR = this.g_cartoon.createCartoonElement("teacher-ranklist-right-btn", "MySprite")
arrowR.ref.init(this.g_cartoon.images.get('t_arrow'));
arrowR.ref.setScaleXY(0);
arrowR.ref.x = this.g_canvasWidth / 2 + 100*this.g_mapScale
arrowR.ref.y = pageLabel.ref.y
arrowR.ref.scaleX *= -1;
arrowR.in = ()=>{
tweenChange(arrowR.ref,{ scaleX: arrowScale*-1, scaleY: arrowScale*-1 }, 0.1 )
}
arrowR.out = ()=>{
tweenChange(arrowR.ref,{ scaleX: 0, scaleY: 0 }, 0.1 )
}
this.render(arrowR.ref);
let m_rankListData = []
let allUserList = {}
let currentPageIndex = 1;
this.subscribeClickEvent("teacher-ranklist-left-btn",()=>{
if(currentPageIndex != 1){
currentPageIndex--;
}
frame.refreshList();
this.g_enableTouch = true;
})
this.subscribeClickEvent("teacher-ranklist-right-btn",()=>{
if(m_rankListData.length > currentPageIndex*5){
currentPageIndex++;
frame.refreshList();
}
this.g_enableTouch = true;
})
frame.setRankListData = (data)=>{
m_rankListData = frame.sortData(data);
frame.refreshList();
}
frame.handleGetData = (data)=>{
allUserList[data.user.uuid] = data;
let dataArray = []
for(let key in allUserList){
dataArray.push(allUserList[key])
}
frame.setRankListData(dataArray)
}
frame.sortData = (data)=>{
data.sort((a,b)=>{
if (a.correctNumber == b.correctNumber) {
return a.totalTime - b.totalTime;
} else {
return b.correctNumber - a.correctNumber;
}
})
return data
}
frame.refreshList = ()=>{
let showDta = this.paginationArray(currentPageIndex,5,m_rankListData)
listItemArray.forEach((listItem, index)=>{
if(showDta[index]){
listItem['num'].text = (currentPageIndex-1)*5 + index + 1 + "";
listItem['name'].text = showDta[index].user.nick_name;
listItem['score'].text = showDta[index].correctNumber + " - " + showDta[index].totalNumber;
listItem['num'].visible = true;
listItem['name'].visible = true;
listItem['score'].visible = true;
listItem['finish'].visible = showDta[index].isComplete;
}else{
listItem['num'].visible = false;
listItem['name'].visible = false;
listItem['score'].visible = false;
listItem['finish'].visible = false;
}
})
pageLabel.ref.text = currentPageIndex + ' / ' + Math.ceil(m_rankListData.length/5)
}
frame.in = ()=>{
pageLabel.in()
arrowL.in()
arrowR.in()
tweenChange(frame.ref,{ scaleX: this.g_mapScale, scaleY: this.g_mapScale }, 0.1 )
}
frame.out = ()=>{
pageLabel.out()
arrowL.out()
arrowR.out()
tweenChange(frame.ref,{ scaleX: 0, scaleY: 0 }, 0.1 )
}
this.render(frame.ref);
}
// ------------------------------------------------------------------------------
// End 初始化 排行榜
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// 初始化 答题页面
// ------------------------------------------------------------------------------
// ==> 题干部分
initAnswer(){
this.initQuestionBackground()
this.initQuestionContainer()
this.initDropDown();
this.initDropDownBackground();
this.initTimer()
this.initAdditionalAudioContainer()
// 选择卡 ChoiceCard1 x:613,y:246
// 选择卡 ChoiceCard2 x:929,y:246
// 选择卡 ChoiceCard3 x:613,y:479
// 选择卡 ChoiceCard4 x:929,y:479
this.initChoiceCard("ChoiceCard1", {x:613,y:246})
this.initChoiceCard("ChoiceCard2", {x:929,y:246})
this.initChoiceCard("ChoiceCard3", {x:613,y:479})
this.initChoiceCard("ChoiceCard4", {x:929,y:479})
}
initQuestionBackground(){
let element = this.g_cartoon.createCartoonElement("question-background", "MySprite",577,720)
element.ref.init(this.g_cartoon.images.get("rectangle-3"))
let scaleY = this.g_canvasHeight / element.ref.height
let x = this.g_cartoon.getOrigin().x + (69 + (element.ref.width * 497/577)/2)*this.g_mapScale
let y = this.g_cartoon.getOrigin().y + (0 + element.ref.height/2)*this.g_mapScale
let readyX = x - 1000 - element.ref.width;
let readyY = y
element.ref.x = readyX;
element.ref.y = readyY;
element.ref.scaleX = this.g_mapScale
element.ref.scaleY = scaleY
element.in = ()=>{
tweenChange(element.ref,{ x: x, y: y }, 0.1 )
}
element.out = ()=>{
tweenChange(element.ref,{ x: readyX, y: readyY }, 0.1 )
}
this.render(element.ref)
}
initReadyGoBackground(){
let element = this.g_cartoon.createCartoonElement("ready-go-background", "MySprite",577,720)
element.ref.init(this.g_cartoon.images.get("bg_ready"))
element.ref.x = this.g_canvasWidth/2
element.ref.y = this.g_canvasHeight/2
element.ref.scaleY = 222*this.g_mapScale / element.ref.height;
element.ref.scaleX = this.g_canvasWidth / element.ref.width;
element.ref.alpha = 0;
element.in = ()=>{
tweenChange(element.ref, { alpha:1 } , 0.2 )
}
element.out = ()=>{
tweenChange(element.ref, { alpha:0 } , 0.2, ()=>{
element.ref.setScaleXY(0)
})
}
this.render(element.ref)
}
initReadyGoContainer(){
let element = this.g_cartoon.createCartoonElement("ready-go-container", "MySprite")
element.ref.init(this.g_cartoon.images.get("bg_1280_222"))
element.ref.x = this.g_canvasWidth/2
element.ref.y = this.g_canvasHeight/2
element.ref.setScaleXY(0);
let ready = new MySprite()
ready.init(this.g_cartoon.images.get("ready"))
ready.x = - this.g_canvasWidth/this.g_mapScale;
ready.y = 0;
let r_sy = 125 / ready.height
let r_sx = 462 / ready.width
ready.scaleY = r_sy * 0.7
ready.scaleX = r_sx * 0.7
element.ref.addChild(ready)
let go = new MySprite()
go.init(this.g_cartoon.images.get("go"))
go.x = - this.g_canvasWidth/this.g_mapScale;
go.y = 0;
let g_sy = 130 / ready.height
let g_sx = 500 / ready.width
go.scaleY = g_sy * 0.7
go.scaleX = g_sx * 0.7
element.ref.addChild(go)
element.readygo = (callback)=>{
this.g_cartoon.playAudio("sm-ready")
tweenChange(ready, { x: 100, y: 0 } , 0.4, ()=>{
ready.scaleY = r_sy
ready.scaleX = r_sx
tweenChange(ready, { x: 0, y: 0 } , 0.1, ()=>{
setTimeout(()=>{
this.g_cartoon.playAudio("sm-go")
tweenChange(ready, { x: this.g_canvasWidth/this.g_mapScale, y: 0 } , 0.3 )
tweenChange(go, { x: 80, y: 0 } , 0.4, ()=>{
go.scaleY = g_sy
go.scaleX = g_sx
setTimeout(()=>{
tweenChange(go, { alpha:0 } , 0.1, ()=>{
element.out(()=>{
callback()
})
})
},300)
})
},300)
})
})
}
element.in = (callback)=>{
this.g_cartoon.getCartoonElement("ready-go-background").in()
tweenChange(element.ref, { scaleX: this.g_mapScale, scaleY: this.g_mapScale } , 0.1 )
element.readygo(callback)
}
element.out = (callback)=>{
this.g_cartoon.getCartoonElement("ready-go-background").out()
tweenChange(element.ref, { scaleY: 0 } , 0.1, ()=>{
callback && callback()
})
}
this.render(element.ref)
}
initQuestionContainer() {
let element = this.g_cartoon.createCartoonElement("question-container", "MySprite",577,720)
element.ref.init(this.g_cartoon.images.get("rectangle-3"))
let x = this.g_cartoon.getOrigin().x + (69 + (element.ref.width * 497/577)/2)*this.g_mapScale
let y = this.g_cartoon.getOrigin().y + (0 + element.ref.height/2)*this.g_mapScale
let readyX = x - 1000 - element.ref.width;
let readyY = y
let downDistance = 180
let downDistance_type2 = 94
element.ref.x = readyX;
element.ref.y = readyY;
element.ref.setScaleXY(this.g_mapScale);
// 卡片内容
let contentWidth = 453;
let contentHeight = 251;
let contentX = 0;
let contentY = - 20*this.g_mapScale;
let currentContent;
let audio_url = "";
element.contentUp = ()=>{
tweenChange(currentContent,{ x: 0, y: 0 }, 0.1 )
}
element.contentDown_type2 = ()=>{
tweenChange(currentContent,{ x: 0, y: downDistance_type2 }, 0.1 )
}
element.contentDown = ()=>{
tweenChange(currentContent,{ x: 0, y: downDistance }, 0.1 )
}
element.setContent = (type?, key?)=>{
if(!type){
element.ref.removeChild(currentContent)
return;
}
switch(type){
case "text":
element.ref.removeChild(currentContent)
currentContent = new MySprite();
currentContent.id = "image"
currentContent.init(this.g_cartoon.images.get("bg-453-251"))
currentContent.x = 0;
currentContent.y = - 20*this.g_mapScale + downDistance;
currentContent.visible = false;
currentContent.setScaleXY(Math.min(contentWidth / currentContent.width, contentHeight / currentContent.height));
let text = new Label();
text.id = "question-text"
text.text = "" + key;
text.fontName = "RoundedBold";
text.fontColor = "#000000";
text.fontSize = 36
text.textAlign = "center";
text.maxSingalLineWidth = 450
currentContent.addChild(text);
element.ref.addChild(currentContent);
break;
case "image":
element.ref.removeChild(currentContent)
currentContent = new MySprite();
currentContent.id = "image"
currentContent.init(this.g_cartoon.images.get(key))
currentContent.x = contentX;
currentContent.y = contentY
currentContent.setScaleXY(Math.min(contentWidth / currentContent.width, contentHeight / currentContent.height));
element.ref.addChild(currentContent);
currentContent.visible = false;
break;
case "audio":
element.ref.removeChild(currentContent)
currentContent = this.g_cartoon.createCartoonElement("dropdown-speaker", "MySprite")
currentContent.ref.id = "audio"
currentContent.ref.init(this.g_cartoon.images.get("speaker-1"))
let scale = Math.min( 120 / currentContent.ref.width, 126 / currentContent.ref.height)
currentContent.ref.x = contentX;
currentContent.ref.y = contentY
audio_url = key;
currentContent.ref.playContentAudio = ()=>{
tweenChange(currentContent, { scaleX: scale*1.2, scaleY: scale*1.2 } , 0.2 )
this.g_cartoon.playAudio(audio_url,false, ()=>{
this.g_cartoon.getCartoonElement("dropdown-speaker").stop();
})
}
currentContent.stop = ()=>{
tweenChange(currentContent, { scaleX: scale, scaleY: scale } , 0.2 )
}
this.subscribeClickEvent("dropdown-speaker",()=>{
if(currentContent.id == "audio"){
currentContent.playContentAudio()
}
this.g_enableTouch = true;
})
this.setAutoPlayQuestionAudio(currentContent.ref.playContentAudio)
currentContent.ref.setScaleXY(scale);
element.ref.addChild(currentContent.ref);
currentContent = currentContent.ref
currentContent.visible = false;
break;
}
setTimeout(()=>{
currentContent.visible = true;
},100)
}
element.in = ()=>{
tweenChange(element.ref,{ x: x, y: y }, 0.1 )
this.g_cartoon.getCartoonElement("question-background").in()
}
element.out = ()=>{
tweenChange(element.ref,{ x: readyX, y: readyY }, 0.1 )
this.g_cartoon.getCartoonElement("question-background").out()
}
this.render(element.ref)
}
initAdditionalAudioContainer(){
let element = this.g_cartoon.createCartoonElement("additional-speaker", "MySprite")
element.ref.id = "Additional_audio";
element.ref.x = this.g_cartoon.getCartoonElementRef("question-container").x
element.ref.init(this.g_cartoon.images.get("speaker-1"))
let scale = Math.min( 120*this.g_mapScale / element.ref.width, 126*this.g_mapScale / element.ref.height)
element.ref.x = this.g_cartoon.getOrigin().x + 320 * this.g_mapScale;
element.ref.y = this.g_cartoon.getOrigin().y + this.g_cartoon.stageHeight - (126*scale)/2 - 30*this.g_mapScale;
let audio_url ;
element.playContentAudio = ()=>{
if(audio_url){
tweenChange(element.ref, { scaleX: scale*1.1, scaleY: scale*1.1 } , 0.2 )
this.g_cartoon.playAudio(audio_url,false, ()=>{
this.g_cartoon.getCartoonElement("additional-speaker").stop();
})
}
}
element.setAduio = (url)=>{
audio_url = url;
this.setAutoPlayQuestionAudio(element.playContentAudio)
}
element.stop = ()=>{
tweenChange(element.ref, { scaleX: scale, scaleY: scale } , 0.2 )
}
element.show = ()=>{
tweenChange(element.ref,{ scaleX: scale, scaleY: scale }, 0.1 )
}
element.hidden = ()=>{
tweenChange(element.ref,{ scaleX: 0, scaleY: 0 }, 0.1 )
}
element.out = ()=>{
tweenChange(element.ref,{ x: element.ref.x - 1000, y: element.ref.y }, 0.1 )
}
this.subscribeClickEvent("additional-speaker",()=>{
if(element.ref.id == "Additional_audio"){
element.playContentAudio()
}
this.g_enableTouch = true;
})
element.ref.setScaleXY(0);
this.render(element.ref);
}
initDropDownBackground(){
let element = this.g_cartoon.createCartoonElement("drop-down-bckground", "MySprite",521,422)
element.ref.init(this.g_cartoon.images.get("rectangle-4"))
let downDistance = this.g_cartoon.getOrigin().y
let x = this.g_cartoon.getOrigin().x + (69 + (element.ref.width * 497/521)/2)*this.g_mapScale
let y = -(element.ref.height/2)*this.g_mapScale
let readyX = x - 1000 - element.ref.width;
let readyY = y
element.ref.x = readyX;
element.ref.y = readyY;
element.ref.scaleX = this.g_mapScale
element.ref.scaleY = this.g_mapScale
element.in = ()=>{
tweenChange(element.ref,{ x: x, y: y }, 0.1 )
}
element.out = ()=>{
tweenChange(element.ref,{ x: readyX, y: readyY }, 0.1 )
}
element.up = ()=>{
tweenChange(element.ref,{ x: x, y: y }, 0.1 )
}
element.down = ()=>{
tweenChange(element.ref,{ x: x, y: y + downDistance }, 0.1 )
}
this.render(element.ref)
}
initDropDown() {
let element = this.g_cartoon.createCartoonElement("drop-down", "MySprite",521,422)
element.ref.init(this.g_cartoon.images.get("drop-down"))
let downDistance = this.g_cartoon.getOrigin().y + 371 * this.g_mapScale
let downDistance_type2 = this.g_cartoon.getOrigin().y + 285 * this.g_mapScale
let x = this.g_cartoon.getOrigin().x + (69 + (element.ref.width * 497/521)/2)*this.g_mapScale
let y = this.g_cartoon.getOrigin().y + (0 + element.ref.height/2)*this.g_mapScale - downDistance
let readyX = x - 1000 - element.ref.width;
let readyY = y
element.ref.x = readyX;
element.ref.y = readyY;
element.ref.setScaleXY(this.g_mapScale);
// 卡片内容位置
let contentWidth = 453;
let contentHeight = 251;
let contentX = 0;
let contentY = - 35*this.g_mapScale;
let currentContent;
let audio_url=""
let number = new Label();
number.text = "Question " + 1 + "/" + 1;
number.fontName = "RoundedBold";
number.fontColor = "#FFFFFF";
number.fontSize = 22
number.textAlign = "center";
number.x = 0;
number.y = + 185;
element.ref.addChild(number);
element.in = ()=>{
this.g_cartoon.getCartoonElement("drop-down-bckground").in()
tweenChange(element.ref,{ x: x, y: y }, 0.1 )
}
element.out = ()=>{
this.g_cartoon.getCartoonElement("drop-down-bckground").out()
tweenChange(element.ref,{ x: readyX, y: readyY }, 0.1 )
}
element.up = ()=>{
this.g_cartoon.getCartoonElement("drop-down-bckground").up()
tweenChange(element.ref,{ x: x, y: y }, 0.1 )
}
element.down = ()=>{
this.g_cartoon.getCartoonElement("drop-down-bckground").down()
tweenChange(element.ref,{ x: x, y: y + downDistance }, 0.1 )
}
element.down_type2 = ()=>{
currentContent.y = currentContent.y + 45
this.g_cartoon.getCartoonElement("drop-down-bckground").down()
tweenChange(element.ref,{ x: x, y: y + downDistance_type2 }, 0.1 )
}
element.setTitleNumber = (current, total)=>{
number.text = "Question " + current + "/" + total;
}
element.setContent = (type, key)=>{
switch(type){
case "text":
element.ref.removeChild(currentContent)
currentContent = new MySprite();
currentContent.id = "image"
currentContent.init(this.g_cartoon.images.get("bg-453-251"))
currentContent.x = 0;
currentContent.y = - 20*this.g_mapScale + downDistance;
currentContent.visible = false;
currentContent.setScaleXY(Math.min(contentWidth / currentContent.width, contentHeight / currentContent.height));
let text = new Label();
text.id = "dropdown-text"
text.text = "" + key;
text.fontName = "RoundedBold";
text.fontColor = "#fad1f3";
text.fontSize = 48
text.textAlign = "center";
text.maxSingalLineWidth = 450
currentContent.addChild(text);
element.ref.addChild(currentContent);
break;
case "image":
element.ref.removeChild(currentContent)
currentContent = new MySprite();
currentContent.id = "image"
currentContent.init(this.g_cartoon.images.get(key))
currentContent.x = contentX;
currentContent.y = contentY
currentContent.setScaleXY(Math.min(contentWidth / currentContent.width, contentHeight / currentContent.height));
element.ref.addChild(currentContent);
currentContent.visible = false;
break;
case "audio":
element.ref.removeChild(currentContent)
currentContent = this.g_cartoon.createCartoonElement("dropdown-speaker", "MySprite")
currentContent.ref.id = "audio"
currentContent.ref.init(this.g_cartoon.images.get("speaker-1"))
let scale = Math.min( 120 / currentContent.ref.width, 126 / currentContent.ref.height)
currentContent.ref.x = contentX;
currentContent.ref.y = contentY
audio_url = key;
currentContent.ref.playContentAudio = ()=>{
tweenChange(currentContent, { scaleX: scale*1.2, scaleY: scale*1.2 } , 0.2 )
this.g_cartoon.playAudio(audio_url,false, ()=>{
this.g_cartoon.getCartoonElement("dropdown-speaker").stop();
})
}
currentContent.stop = ()=>{
tweenChange(currentContent, { scaleX: scale, scaleY: scale } , 0.2 )
}
this.subscribeClickEvent("dropdown-speaker",()=>{
if(currentContent.id == "audio"){
currentContent.playContentAudio()
}
this.g_enableTouch = true;
})
this.setAutoPlayQuestionAudio(currentContent.ref.playContentAudio)
currentContent.ref.setScaleXY(scale);
element.ref.addChild(currentContent.ref);
currentContent = currentContent.ref;
currentContent.visible = false;
break;
}
setTimeout(()=>{
currentContent.visible = true;
},100)
}
this.render(element.ref)
}
// 题干部分 <== 结束
// 定时器
initTimer(){
let element = this.g_cartoon.createCartoonElement("timer", "MySprite",105,105)
element.ref.init(this.g_cartoon.images.get("combined-shape"))
let x = this.g_cartoon.getOrigin().x + (863 + element.ref.width/2)*this.g_mapScale
let y = this.g_cartoon.getOrigin().y + (71 + element.ref.height/2)*this.g_mapScale
let readyX = x
let readyY = y - 500 - element.ref.height;
element.ref.x = readyX;
element.ref.y = readyY;
element.ref.setScaleXY(this.g_mapScale);
let isRun = false;
const initTime = 10;
// 时间显示
let count = new Label();
count.text = "-";
count.fontName = "RoundedBold";
count.fontColor = "#fad1f3";
count.fontSize = 48
count.textAlign = "center";
count.x = 0;
count.y = 0;
element.ref.addChild(count);
let circleStep = 0.1;
let currentPercent = 0;
let circle = new ShapeCircle()
circle.setRadius(47)
circle.drawType = "stroke"
circle.strokeColor = "#702dee";
circle.strokeLineWidth = 13;
circle.startRadian = this.convertPercentToRadian(0,true);
circle.endRadian = this.convertPercentToRadian(0.5,true);
circle.counterclockwise = true;
element.ref.addChild(circle);
// 计时变量
let subTime = 0;
let totalTime = 0;
let remind3Sec = true;
let timeRemaining = initTime;
// 计时器到时回调
let _callback;
let setInter = (s)=>{
let timeOut = (s)=>{
setTimeout(()=>{
if(isRun){
timeRemaining--;
subTime++;
currentPercent += circleStep;
circle.endRadian = this.convertPercentToRadian(currentPercent,true);
if(timeRemaining < 0){
isRun = false;
element.ref.children[1].text = "0";
count.fontColor = "#ff2846";
circle.strokeColor = "#ff2846";
circle.visible = false;
element.ref.init(this.g_cartoon.images.get("red-circle"))
_callback && _callback()
}else{
if(remind3Sec && timeRemaining/100<3 ){
this.g_cartoon.getCartoonElement("timer")._in3Sec()
remind3Sec = false;
}
element.ref.children[1].text = Math.floor(timeRemaining/100) + 1 + "";
timeOut(s);
}
}
},s)
}
timeOut(s);
}
element.in = ()=>{
tweenChange(element.ref,{ x: x, y: y }, 0.1 )
}
element.out = ()=>{
tweenChange(element.ref,{ x: readyX, y: readyY }, 0.1 )
}
element.run = ()=>{
isRun = true;
setInter(10)
}
element.stop = ()=>{
isRun = false;
totalTime += subTime;
}
element.reset = (initTime)=>{
isRun = false;
subTime = 0
timeRemaining = initTime * 100; // initTime 的单位是秒 在定时器中的定时单位是10毫秒 所有要放大100倍
remind3Sec = true; // 重置3秒倒计时提醒
element.ref.children[1].text = "" + initTime;
count.fontColor = "#fad1f3";
element.ref.init(this.g_cartoon.images.get("combined-shape"))
circleStep = 1/(initTime*100)
circle.visible = true;
currentPercent = 0;
circle.strokeColor = "#702dee";
circle.startRadian = this.convertPercentToRadian(0,true);
circle.endRadian = this.convertPercentToRadian(0,true);
}
import { element._in3Sec = ()=>{
Label, this.g_cartoon.playAudio("sm-choice-timeup-3")
MySprite, tweenChange, }
} from './Unit'; element.subscribeTimeup = (callback:Function)=>{
import {res, resAudio} from './resources'; _callback = callback
}
element.getTotalTime = ()=>{
return Math.floor(totalTime/100);
}
this.render(element.ref)
}
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import TWEEN from '@tweenjs/tween.js'; // 选择卡 ChoiceCard1 x:613 y:246
// 选择卡 ChoiceCard2 x:929 y:246
// 选择卡 ChoiceCard3 x:613 y:479
// 选择卡 ChoiceCard4 x:929 y:246
initChoiceCard(choiceCardKey, position){
let element = this.g_cartoon.createCartoonElement(choiceCardKey, "MySprite",305,223)
element.ref.init(this.g_cartoon.images.get("choice-card-typeA"))
let x = this.g_cartoon.getOrigin().x + (position.x + element.ref.width/2)*this.g_mapScale
let y = this.g_cartoon.getOrigin().y + (position.y + element.ref.height/2)*this.g_mapScale
let readyX = x
let readyY = y// - 500 - element.ref.height;
element.ref.x = readyX;
element.ref.y = readyY;
element.ref.setScaleXY(0);
// 文字
let textContent = new Label();
textContent.text = "Demo";
textContent.fontName = "RoundedBold";
textContent.fontColor = "#6341af";
textContent.fontSize = 36
textContent.textAlign = "center";
textContent.x = 0;
textContent.y = -50;
textContent.visible = false;
textContent.maxSingalLineWidth = 200 * this.g_mapScale
element.ref.addChild(textContent);
// 图片
let imageContent = new MySprite();
imageContent.init(this.g_cartoon.images.get("bg-240-180"))
let sx = imageContent.width / 240;
let sy = imageContent.height / 180;
imageContent.x = 0;
imageContent.y = -50;
imageContent.visible = false;
imageContent.setScaleXY(Math.min(sx,sy))
imageContent.visible = false;
element.ref.addChild(imageContent);
// 右上角正确图标
let correctIcon = new MySprite();
correctIcon.init(this.g_cartoon.images.get("correct-icon"))
correctIcon.x = 105;
correctIcon.y = -85
correctIcon.setScaleXY(Math.min( 40 / correctIcon.width, 40 / correctIcon.height));
correctIcon.visible = false;
element.ref.addChild(correctIcon);
// 右上角错误图标
let incorrectIcon = new MySprite();
incorrectIcon.init(this.g_cartoon.images.get("incorrect-icon"))
incorrectIcon.x = 105;
incorrectIcon.y = -85
incorrectIcon.setScaleXY(Math.min(35 / incorrectIcon.width, 35 / incorrectIcon.height));
incorrectIcon.visible = false;
element.ref.addChild(incorrectIcon);
// 是否是正确选项
let isCorrectAnswer = false;
element.in = ()=>{
tweenChange(element.ref,{ scaleX: this.g_mapScale, scaleY: this.g_mapScale }, 0.1 )
}
element.out = ()=>{
tweenChange(element.ref,{ scaleX: 0, scaleY: 0 }, 0.1 )
}
element.correct = ()=>{
correctIcon.visible = true;
textContent.fontColor = "#FFFFFF"
textContent.fontSize = 34
element.ref.init(this.g_cartoon.images.get("choice-card-typeD"))
this.showCorrectPatal(choiceCardKey,2000)
}
element.error = ()=>{
textContent.fontColor = "#FFFFFF"
incorrectIcon.visible = true;
element.ref.init(this.g_cartoon.images.get("choice-card-typeB"))
}
element.normal = ()=>{
textContent.fontColor = "#FFFFFF"
element.ref.init(this.g_cartoon.images.get("choice-card-typeC"))
}
element.ready = ()=>{
textContent.fontColor = "#6341af"
textContent.fontSize = 36
element.ref.init(this.g_cartoon.images.get("choice-card-typeA"))
correctIcon.visible = false;
incorrectIcon.visible = false;
}
element.setChoice = (setting)=>{
if(setting.isText){
textContent.text = setting.text;
isCorrectAnswer = setting.answer
textContent.visible = true;
imageContent.visible = false;
}else{
isCorrectAnswer = setting.answer
imageContent.init(this.g_cartoon.images.get(setting.image_url))
let sx = 240 / imageContent.width;
let sy = 180 / imageContent.height;
imageContent.x = 0;
imageContent.y = -5;
textContent.visible = false;
imageContent.visible = true;
imageContent.setScaleXY(Math.min(sx,sy))
}
}
element.showAnswer = ()=>{
element.normal()
if(isCorrectAnswer){
correctIcon.visible = true;
}
}
this.subscribeClickEvent(choiceCardKey, ()=>{
this.handleClickChoice(choiceCardKey, isCorrectAnswer)
})
this.render(element.ref)
}
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// 初始化 排行榜
// ------------------------------------------------------------------------------
initRankingList(){
let element = this.g_cartoon.createCartoonElement("ranking-list", "MySprite", 756, 676)
element.ref.init(this.g_cartoon.images.get("complete-card"))
let x = this.g_cartoon.getOrigin().x + (929 + element.ref.width/2)*this.g_mapScale
let y = this.g_cartoon.getOrigin().y + (479 + element.ref.height/2)*this.g_mapScale
element.ref.x = this.g_canvasWidth / 2;
element.ref.y = this.g_canvasHeight / 2;
element.ref.setScaleXY(0);
let X1 = -164;
let X2 = -90;
let X3 = 120;
let X4 = 235;
let header = []
let name = []
let correctNumber = []
let time = []
let pos_Y = [-170,-35,108,236]
for(let index=0; index<4; index++){
let line_1_Header = new MySprite();
line_1_Header.init(this.g_cartoon.images.get("header"))
line_1_Header.x = X1;
line_1_Header.y = pos_Y[index];
line_1_Header.visible = false;
line_1_Header.setScaleXY(Math.min( 60 / line_1_Header.width, 60 / line_1_Header.height));
element.ref.addChild(line_1_Header);
header.push(line_1_Header)
let line_1_Name = new Label();
line_1_Name.text = "Mildddddddddddddddes";
line_1_Name.fontName = "BerlinSansFBDemi-Bold";
line_1_Name.fontColor = "#acacac";
line_1_Name.fontSize = 24
line_1_Name.textAlign = "center";
line_1_Name.x = X2;
line_1_Name.y = pos_Y[index];
line_1_Name.visible = false;
element.ref.addChild(line_1_Name);
name.push(line_1_Name)
let line_1_CorrectNumber = new Label();
line_1_CorrectNumber.text = "1dss2";
line_1_CorrectNumber.fontName = "BerlinSansFBDemi-Bold";
line_1_CorrectNumber.fontColor = "#3d3d3d";
line_1_CorrectNumber.fontSize = 48
line_1_CorrectNumber.textAlign = "center";
line_1_CorrectNumber.x = X3;
line_1_CorrectNumber.y = pos_Y[index];
line_1_CorrectNumber.visible = false;
element.ref.addChild(line_1_CorrectNumber);
correctNumber.push(line_1_CorrectNumber)
let line_1_Time = new Label();
line_1_Time.text = "5dd3s";
line_1_Time.fontName = "BerlinSansFBDemi-Bold";
line_1_Time.fontColor = "#acacac";
line_1_Time.fontSize = 24
line_1_Time.textAlign = "center";
line_1_Time.x = X4;
line_1_Time.y = pos_Y[index];
line_1_Time.visible = false;
element.ref.addChild(line_1_Time);
time.push(line_1_Time)
}
let meIcon = new MySprite();
meIcon.init(this.g_cartoon.images.get("me"))
meIcon.x = 0;
meIcon.y = 0;
meIcon.visible = false;
meIcon.setScaleXY(Math.min( 24 / meIcon.width, 24 / meIcon.height));
element.ref.addChild(meIcon);
@Component({ element.in = ()=>{
selector: 'app-play', tweenChange(element.ref,{ scaleX: this.g_mapScale, scaleY: this.g_mapScale }, 0.1 )
templateUrl: './play.component.html', }
styleUrls: ['./play.component.css'] element.out = ()=>{
}) tweenChange(element.ref,{ scaleX: 0, scaleY: 0 }, 0.1 )
export class PlayComponent implements OnInit, OnDestroy { }
element.setMeIcon = (index)=>{
let x = header[index].x -22
let y = header[index].y -22
meIcon.x = x;
meIcon.y = y;
meIcon.visible = true;
}
element.setList = (item, index)=>{
item = {
header_url: this.g_cartoon.images.get("header"),
name: "Miles",
correctNumber: "" + this.m_correctNumber,
time: "" + this.m_totalTime + "s"
}
header[index].init(this.g_cartoon.images.get(item.header_url))
header[index].setScaleXY(Math.min( 60 / header[index].width, 60 / header[index].height));
header[index].visible = true;
name[index].text = item.name;
name[index].visible = true;
correctNumber[index].text = item.correctNumber;
correctNumber[index].visible = true;
time[index].text = item.time;
time[index].visible = true;
}
element.hiddeAllItem = ()=>{
header.forEach((item)=>{
item.visible = false;
})
name.forEach((item)=>{
item.visible = false;
})
correctNumber.forEach((item)=>{
item.visible = false;
})
time.forEach((item)=>{
item.visible = false;
})
meIcon.visible = false;
}
this.render(element.ref)
}
@ViewChild('canvas', {static: true }) canvas: ElementRef;
@ViewChild('wrap', {static: true }) wrap: ElementRef;
// 数据 // ------------------------------------------------------------------------------
data;
ctx;
canvasWidth = 1280; // canvas实际宽度
canvasHeight = 720; // canvas实际高度
canvasBaseW = 1280; // canvas 资源预设宽度
canvasBaseH = 720; // canvas 资源预设高度
mx; // 点击x坐标
my; // 点击y坐标
// 资源
rawImages = new Map(res);
rawAudios = new Map(resAudio);
images = new Map();
animationId: any;
winResizeEventStream = new Subject();
audioObj = {};
renderArr;
mapScale = 1;
canvasLeft;
canvasTop;
saveKey = 'test_0011';
btnLeft;
btnRight;
pic1;
pic2;
canTouch = true;
curPic;
@HostListener('window:resize', ['$event'])
onResize(event) {
this.winResizeEventStream.next();
}
ngOnInit() {
this.data = {};
// 获取数据
const getData = (<any> window).courseware.getData;
getData((data) => {
if (data && typeof data == 'object') {
this.data = data;
}
// console.log('data:' , data);
// 初始化 各事件监听
this.initListener();
// 若无数据 则为预览模式 需要填充一些默认数据用来显示
this.initDefaultData();
// 初始化 音频资源
this.initAudio();
// 初始化 图片资源
this.initImg();
// 开始预加载资源
this.load();
}, this.saveKey);
}
// --------------------------------------------------
// -------------- Template function ---------------
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
//
// _________
// / /.
// .-------------. /_________/ |
// / / | | | |
// /+============+\ | | |====| | |
// ||C:\> || | | | |
// || || | | |====| | |
// || || | | ___ | |
// || || | | |166| | |
// || ||/@@@ | --- | |
// \+============+/ @ |_________|./.
// @ .. ....'
// ..................@ __.'.' ''
// /oooooooooooooooo// ///
// /................// /_/
// ------------------
//
// --------------------------------------------------
@ViewChild("canvas") canvas: ElementRef;
@ViewChild("wrap") wrap: ElementRef;
@HostListener("window:resize", ["$event"])
onResize(event) {
this.g_winResizeEventStream.next();
}
ngOnDestroy() { ngOnDestroy() {
window['curCtx'] = null; window["curCtx"] = null;
window.cancelAnimationFrame(this.animationId); window.cancelAnimationFrame(this.g_animationId);
}
ngOnInit() {
const getData = (<any>window).courseware.getData;
getData((data, aspect) => {
if (aspect) {
console.log('aspect : ', aspect);
this.g_serverAllUser = aspect.all_user;
}
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 = {};
}
load() { this.initDefaultData();
this.initAudio();
this.initImg();
// 预加载资源 // 预加载资源
this.loadResources().then(() => { this.g_cartoon.loadResources().then(() => {
window["air"].hideAirClassLoading(this.saveKey, this.data); this.initSystem();
this.init();
this.update(); this.update();
this.systemReady()
window["air"].hideAirClassLoading(this.g_KEY, this.g_data);
}); });
this.initListener();
}, this.g_KEY);
} }
// ----------------------------------
// 初始化默认数据
// ----------------------------------
initDefaultData() {
if ( Object.keys(this.g_formData).length===0 ) {
// console.log("Init default form data")
this.g_formData = defauleFormData;
}
}
init() {
this.initCtx(); // ----------------------------------
this.initData(); // 初始化音乐
this.initView(); // ----------------------------------
initAudio() {
const contentObj = this.g_formData;
if (!contentObj) {
return;
}
const arr = contentObj.dataArray;
// 添加用户上传音效
if (arr) {
for (let i = 0; i < arr.length; i++) {
if(arr[i].question.audio_url){
this.g_cartoon.addAudio(arr[i].question.audio_url, arr[i].question.audio_url);
}
}
}
// 添加本地音效
for( var key in localAudios ){
this.g_cartoon.addAudio( key, localAudios[key] );
}
} }
initCtx() {
this.canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight;
this.canvas.nativeElement.width = this.wrap.nativeElement.clientWidth;
this.canvas.nativeElement.height = this.wrap.nativeElement.clientHeight;
this.ctx = this.canvas.nativeElement.getContext('2d'); // ----------------------------------
this.canvas.nativeElement.width = this.canvasWidth; // 初始化图片
this.canvas.nativeElement.height = this.canvasHeight; // ----------------------------------
initImg() {
const contentObj = this.g_formData;
if (contentObj) {
const addPicUrl = url => {
if (url) {
this.g_cartoon.addImage(url, url);
}
};
const arr = this.g_data.contentObj.dataArray;
if (arr) {
for (let i = 0; i < arr.length; i++) {
addPicUrl(arr[i].question.image_url);
addPicUrl(arr[i].choice.correct.image_url);
arr[i].choice.incorrect.forEach(item=>{
addPicUrl(item.image_url);
})
}
}
}
// 添加本地图片
for( var key in localImages ){
this.g_cartoon.addImage( key, localImages[key] );
}
}
window['curCtx'] = this.ctx; mapDown(event) {
if (!this.g_enableTouch) {
return;
}
for(let cartoonID in this.m_clickQueue){
if (this.checkClickTarget(this.g_cartoon.getCartoonElementRef(cartoonID))) {
this.g_enableTouch = false;
this.m_clickQueue[cartoonID]();
return;
}
} }
}
mapMove(event) {}
mapUp(event) {}
update() {
this.g_animationId = window.requestAnimationFrame(this.update.bind(this));
// 清除画布内容
this.g_ctx.clearRect(0, 0, this.g_canvasWidth, this.g_canvasHeight);
TWEEN.update();
this.updateArr(this.m_renderArr);
this.updateArr(this.m_endPageArr);
this.updateArr(this.m_elementPetalArr);
}
updateItem(item) { updateItem(item) {
if (item) { if (item) {
...@@ -154,6 +2095,7 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -154,6 +2095,7 @@ export class PlayComponent implements OnInit, OnDestroy {
} }
} }
updateArr(arr) { updateArr(arr) {
if (!arr) { if (!arr) {
return; return;
...@@ -164,209 +2106,131 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -164,209 +2106,131 @@ export class PlayComponent implements OnInit, OnDestroy {
} }
initListener() {
this.g_winResizeEventStream.pipe(debounceTime(500)).subscribe(data => {
this.renderAfterResize();
});
if (this.IsPC()) {
this.canvas.nativeElement.addEventListener("mousedown", event => {
setMxMyByMouse(event);
this.mapDown(event);
});
this.canvas.nativeElement.addEventListener("mousemove", event => {
setMxMyByMouse(event);
this.mapMove(event);
});
this.canvas.nativeElement.addEventListener("mouseup", event => {
setMxMyByMouse(event);
this.mapUp(event);
});
const setMxMyByMouse = event => {
this.g_clickX = event.offsetX;
this.g_clickY = event.offsetY;
};
} else {
this.canvas.nativeElement.addEventListener("touchstart", event => {
setMxMyByTouch(event);
this.mapDown(event);
});
initListener() { this.canvas.nativeElement.addEventListener("touchmove", event => {
setMxMyByTouch(event);
this.mapMove(event);
});
this.winResizeEventStream this.canvas.nativeElement.addEventListener("touchend", event => {
.pipe(debounceTime(500)) setMxMyByTouch(event);
.subscribe(data => { this.mapUp(event);
this.renderAfterResize();
}); });
this.canvas.nativeElement.addEventListener("touchcancel", event => {
setMxMyByTouch(event);
this.mapUp(event);
});
// --------------------------------------------- const setMxMyByTouch = event => {
const setParentOffset = () => {
const rect = this.canvas.nativeElement.getBoundingClientRect();
this.canvasLeft = rect.left;
this.canvasTop = rect.top;
};
const setMxMyByTouch = (event) => {
if (event.touches.length <= 0) { if (event.touches.length <= 0) {
return; return;
} }
if (this.canvasLeft == null) {
if (this.g_canvasLeft == null) {
setParentOffset(); setParentOffset();
} }
this.mx = event.touches[0].pageX - this.canvasLeft;
this.my = event.touches[0].pageY - this.canvasTop;
};
const setMxMyByMouse = (event) => { this.g_clickX = event.touches[0].pageX - this.g_canvasLeft;
this.mx = event.offsetX; this.g_clickY = event.touches[0].pageY - this.g_canvasTop;
this.my = event.offsetY;
}; };
// ---------------------------------------------
let firstTouch = true; const setParentOffset = () => {
const rect = this.canvas.nativeElement.getBoundingClientRect();
const touchDownFunc = (e) => { this.g_canvasLeft = rect.left;
if (firstTouch) { this.g_canvasTop = rect.top;
firstTouch = false;
removeMouseListener();
}
setMxMyByTouch(e);
this.mapDown(e);
};
const touchMoveFunc = (e) => {
setMxMyByTouch(e);
this.mapMove(e);
};
const touchUpFunc = (e) => {
setMxMyByTouch(e);
this.mapUp(e);
}; };
const mouseDownFunc = (e) => {
if (firstTouch) {
firstTouch = false;
removeTouchListener();
} }
setMxMyByMouse(e);
this.mapDown(e);
};
const mouseMoveFunc = (e) => {
setMxMyByMouse(e);
this.mapMove(e);
};
const mouseUpFunc = (e) => {
setMxMyByMouse(e);
this.mapUp(e);
};
const 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 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);
};
addMouseListener();
addTouchListener();
} }
playAudio(key, now = false, callback = null) { showArr(arr) {
if (!arr) {
const audio = this.audioObj[key]; return;
if (audio) {
if (now) {
audio.pause();
audio.currentTime = 0;
}
if (callback) {
audio.onended = () => {
callback();
};
} }
audio.play(); for (let i = 0; i < arr.length; i++) {
arr[i].visible = true;
} }
} }
hideArr(arr) {
if (!arr) {
return;
}
for (let i = 0; i < arr.length; i++) {
arr[i].visible = false;
}
}
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); IsPC() {
}); if (window["ELECTRON"]) {
return Promise.all(pr); return false; // 封装客户端标记
} }
if (
preload(url) { document.body.ontouchmove !== undefined &&
return new Promise((resolve, reject) => { document.body.ontouchmove !== undefined
const img = new Image(); ) {
// img.crossOrigin = "anonymous"; return false;
img.onload = () => resolve(img); } else {
img.onerror = reject; return true;
img.src = url;
});
} }
preloadAudio(url) {
return new Promise((resolve, reject) => {
const audio = new Audio();
audio.oncanplay = (a) => {
resolve();
};
audio.onerror = () => {
reject();
};
audio.src = url;
audio.load();
});
} }
renderAfterResize() { renderAfterResize() {
this.canvasWidth = this.wrap.nativeElement.clientWidth; this.g_canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight; this.g_canvasHeight = this.wrap.nativeElement.clientHeight;
this.init(); this.update();
this.handleScreenResize()
} }
checkClickTarget(target) { checkClickTarget(target) {
if (!target) {
return false;
}
const rect = target.getBoundingBox(); const rect = target.getBoundingBox();
if (this.checkPointInRect(this.g_clickX, this.g_clickY, rect)) {
if (this.checkPointInRect(this.mx, this.my, rect)) {
return true; return true;
} }
return false; return false;
} }
getWorlRect(target) {
getWorlRect(target) {
let rect = target.getBoundingBox(); let rect = target.getBoundingBox();
if (target.parent) { if (target.parent) {
const pRect = this.getWorlRect(target.parent); const pRect = this.getWorlRect(target.parent);
rect.x += pRect.x; rect.x += pRect.x;
rect.y += pRect.y; rect.y += pRect.y;
...@@ -374,6 +2238,7 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -374,6 +2238,7 @@ export class PlayComponent implements OnInit, OnDestroy {
return rect; return rect;
} }
checkPointInRect(x, y, rect) { checkPointInRect(x, y, rect) {
if (x >= rect.x && x <= rect.x + rect.width) { if (x >= rect.x && x <= rect.x + rect.width) {
if (y >= rect.y && y <= rect.y + rect.height) { if (y >= rect.y && y <= rect.y + rect.height) {
...@@ -384,296 +2249,348 @@ export class PlayComponent implements OnInit, OnDestroy { ...@@ -384,296 +2249,348 @@ export class PlayComponent implements OnInit, OnDestroy {
} }
getPosByAngle(angle, len) {
const radian = (angle * Math.PI) / 180;
const x = Math.sin(radian) * len;
addUrlToAudioObj(key, url = null, vlomue = 1, loop = false, callback = null) { const y = Math.cos(radian) * len;
return { x, y };
const audioObj = this.audioObj;
if (url == null) {
url = key;
} }
this.rawAudios.set(key, url);
const audio = new Audio();
audio.src = url;
audio.load();
audio.loop = loop;
audio.volume = vlomue;
audioObj[key] = audio; getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx;
if (callback) { const _y = ey - sy;
audio.onended = () => { const len = Math.sqrt(Math.pow(_x, 2) + Math.pow(_y, 2));
callback(); return len;
};
}
}
addUrlToImages(url) {
this.rawImages.set(url, url);
} }
subscribeClickEvent(id,callback){
this.m_clickQueue[id] = callback
}
// 全局初始化入口,当资源加载完毕后执行
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.g_enableTouch = 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();
}
/**
* 添加默认数据 便于无数据时的展示
*/
initDefaultData() {
if (!this.data.pic_url) { initStage() {
this.data.pic_url = 'assets/play/default/pic.jpg'; const bgWidth = 1280;
this.data.pic_url_2 = 'assets/play/default/pic.jpg'; const bgHeight = 720;
this.g_cartoon.stageWidth = bgWidth*this.g_mapScale;
this.g_cartoon.stageHeight= bgHeight*this.g_mapScale;
const imageColor = this.g_cartoon.createCartoonElement("background-color", "ShapeRect").ref;
// console.log( "stageWidth: " + this.g_cartoon.stageWidth + " stageHeight" + this.g_cartoon.stageHeight)
// console.log( "clientWidth: " + this.g_cartoon.clientWidth + " clientHeight" + this.g_cartoon.clientHeight)
// console.log( "canvasWidth: " + this.g_canvasWidth + " canvasHeight" + this.g_canvasHeight)
// console.log( "mapScale: " + this.g_mapScale )
imageColor.x = this.g_cartoon.clientWidth / 2 ;
imageColor.y = this.g_cartoon.clientHeight / 2 ;
imageColor.setSize(this.g_cartoon.clientWidth, this.g_cartoon.clientHeight);
imageColor.init();
if(this.g_EnableStageRuler){
imageColor.fillColor = '#BE3C38';
} }
this.m_renderArr.push(imageColor);
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.m_renderArr.push(image);
this.g_stage = image
} }
render(ele){
/** this.m_renderArr.push(ele);
* 添加预加载图片
*/
initImg() {
this.addUrlToImages(this.data.pic_url);
this.addUrlToImages(this.data.pic_url_2);
} }
/** sendServerEvent(key, data) {
* 添加预加载音频 const c = (<any> window).courseware;
*/ c.sendEvent(key, JSON.stringify(data));
initAudio() { }
// 音频资源
this.addUrlToAudioObj(this.data.audio_url);
this.addUrlToAudioObj(this.data.audio_url_2);
// 音效 addServerListener(msg_key, callback) {
this.addUrlToAudioObj('click', this.rawAudios.get('click'), 0.3); 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);
}
/**
* 初始化数据
*/
initData() {
const sx = this.canvasWidth / this.canvasBaseW;
const sy = this.canvasHeight / this.canvasBaseH;
const s = Math.min(sx, sy);
this.mapScale = s;
// this.mapScale = sx;
// this.mapScale = sy;
this.renderArr = [];
}
/**
* 初始化试图
*/
initView() {
this.initPic();
this.initBottomPart();
}
initBottomPart() {
const btnLeft = new MySprite();
btnLeft.init(this.images.get('btn_left'));
btnLeft.x = this.canvasWidth - 150 * this.mapScale;
btnLeft.y = this.canvasHeight - 100 * this.mapScale;
btnLeft.setScaleXY(this.mapScale);
this.renderArr.push(btnLeft);
this.btnLeft = btnLeft;
const btnRight = new MySprite();
btnRight.init(this.images.get('btn_right'));
btnRight.x = this.canvasWidth - 50 * this.mapScale;
btnRight.y = this.canvasHeight - 100 * this.mapScale;
btnRight.setScaleXY(this.mapScale);
this.renderArr.push(btnRight);
this.btnRight = btnRight;
}
initPic() {
const maxW = this.canvasWidth * 0.7;
const pic1 = new MySprite();
pic1.init(this.images.get(this.data.pic_url));
pic1.x = this.canvasWidth / 2;
pic1.y = this.canvasHeight / 2;
pic1.setScaleXY(maxW / pic1.width);
this.renderArr.push(pic1); // --------------------------------------------------
this.pic1 = pic1; // -------------- Template function ---------------
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
//
// .-~~~~~~~~~-._ _.-~~~~~~~~~-.
// __.' ~. .~ `.__
// .'// \./ \\`.
// .'// | \\`.
// .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`.
// .'//.-" `-. | .-' "-.\\`.
// .'//______.============-.. \ | / ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
// --------------------------------------------------
// showParticle( element_id ) 泡泡效果
// --------------------------------------------------
// showEndPatal() / stopEndPatal() 花瓣飘落结束动画
// --------------------------------------------------
// showCorrectPatal() 指定元素上面飘花
// --------------------------------------------------
// convertPercentToRadian() 将百分比转换为弧长 第一个参数是百分比,第二个参数是方向 true为逆时针,false为顺时针。用于ShapeCircle换圆弧
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
// --------------------------------------------------
const label1 = new Label();
label1.text = this.data.text;
label1.textAlign = 'center';
label1.fontSize = 50;
label1.fontName = 'BRLNSDB';
label1.fontColor = '#ffffff';
pic1.addChild(label1); // 泡泡
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);
}
// 选择正确动画
showCorrectPatal(card_id, showTime) {
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = true;
this.addCorrectPetal(card_id);
setTimeout(()=>{
this.m_elementPetalArr = [];
this.m_showElementPetalFlag = false;
},showTime)
}
addCorrectPetal(card_id) {
if (!this.m_showElementPetalFlag) {
return;
}
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 pic2 = new MySprite(); const randomS = (Math.random() * 0.4 + 0.6) * this.g_mapScale * 0.5;
pic2.init(this.images.get(this.data.pic_url_2)); petal.setScaleXY(randomS);
pic2.x = this.canvasWidth / 2 + this.canvasWidth;
pic2.y = this.canvasHeight / 2;
pic2.setScaleXY(maxW / pic2.width);
this.renderArr.push(pic2); const randomR = Math.random() * 360;
this.pic2 = pic2; petal.rotation = randomR;
this.curPic = pic1; const randomX = Math.random() * element.ref.width * this.g_mapScale;
}
petal.x = element.ref.x - (element.ref.width * this.g_mapScale / 2) + randomX;
petal.y = element.ref.y - (element.ref.height * this.g_mapScale / 2);
btnLeftClicked() { const randomT = 1 + Math.random() * 2;
petal["time"] = randomT;
this.lastPage(); let randomTR = 360 * Math.random(); // - 180;
if (Math.random() < 0.5) {
randomTR *= -1;
} }
petal["tr"] = randomTR;
btnRightClicked() {
this.m_elementPetalArr.push(petal);
this.nextPage(); 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);
} }
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, () => { showEndPatal() {
this.canTouch = true; this.m_endPageArr = [];
this.curPic = this.pic1; this.m_showPetalFlag = true;
}); this.addPetal();
} }
nextPage() { stopEndPatal() {
this.m_endPageArr = [];
this.m_showPetalFlag = false;
}
if (this.curPic == this.pic2) { addPetal() {
if (!this.m_showPetalFlag) {
return; return;
} }
const petal = this.getPetal();
this.canTouch = false; this.m_endPageArr.push(petal);
moveItem(
const moveLen = this.canvasWidth; petal,
tweenChange(this.pic1, {x: this.pic1.x - moveLen}, 1); petal.x,
tweenChange(this.pic2, {x: this.pic2.x - moveLen}, 1, () => { this.g_canvasHeight + petal.height * petal.scaleY,
this.canTouch = true; petal["time"],
this.curPic = this.pic2; () => {
}); removeItemFromArr(this.m_endPageArr, petal);
} }
);
pic1Clicked() { rotateItem(petal, petal["tr"], petal["time"]);
this.playAudio(this.data.audio_url); setTimeout(() => {
this.addPetal();
}, 100);
} }
pic2Clicked() { getPetal() {
this.playAudio(this.data.audio_url_2); const petal = new MySprite(this.g_ctx);
}
const id = Math.ceil(Math.random() * 3);
petal.init(this.g_cartoon.images.get(this.m_PetalImage + id));
const randomS = (Math.random() * 0.4 + 0.6) * this.g_mapScale;
petal.setScaleXY(randomS);
const randomR = Math.random() * 360;
petal.rotation = randomR;
const randomX = Math.random() * this.g_canvasWidth;
petal.x = randomX;
petal.y = (-petal.height / 2) * petal.scaleY;
mapDown(event) { const randomT = 2 + Math.random() * 5;
petal["time"] = randomT;
if (!this.canTouch) { let randomTR = 360 * Math.random(); // - 180;
return; if (Math.random() < 0.5) {
randomTR *= -1;
} }
petal["tr"] = randomTR;
if ( this.checkClickTarget(this.btnLeft) ) { return petal;
this.btnLeftClicked();
return;
} }
if ( this.checkClickTarget(this.btnRight) ) {
this.btnRightClicked();
return;
}
if ( this.checkClickTarget(this.pic1) ) { showJellyAnimation(element_id){
this.pic1Clicked(); let element = this.g_cartoon.getCartoonElement(element_id).ref
return; tweenChange(element,{ scaleX: this.g_mapScale * 1.1 , scaleY: this.g_mapScale * 1.1 }, 0.1, ()=>{
tweenChange(element,{ scaleX: this.g_mapScale * 0.9 , scaleY: this.g_mapScale * 0.9 }, 0.1, ()=>{
tweenChange(element,{ scaleX: this.g_mapScale , scaleY: this.g_mapScale }, 0.1 )
})
})
} }
if ( this.checkClickTarget(this.pic2) ) { showShakeAnimation(element_id){
this.pic2Clicked(); let element = this.g_cartoon.getCartoonElement(element_id).ref
return; 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 )
})
})
} }
convertPercentToRadian(per, direction){
let radian = 0;
if(direction) { //逆时针
if(per*360 > 270){
radian = 361 - (per*360 - 270)
}else{
radian = 270 - per*360
} }
}else{ //顺时针
mapMove(event) { if(per*360 > 90){
radian = per*360 - 90
}else{
radian = 270 + per*360
} }
mapUp(event) {
} }
return (radian * Math.PI) / 180;
update() {
// ----------------------------------------------------------
this.animationId = window.requestAnimationFrame(this.update.bind(this));
// 清除画布内容
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
// tween 更新动画
TWEEN.update();
// ----------------------------------------------------------
this.updateArr(this.renderArr);
} }
} }
const res = [ const localImages = {
'startBtn': "assets/play/btn-start.png",
'restartBtn': "assets/play/btn-restart.png",
'petal_1': "assets/play/scrap-pic-1.png",
'petal_2': "assets/play/scrap-pic-2.png",
'petal_3': "assets/play/scrap-pic-3.png",
'bg_1280_720_Ruler': "assets/play/1280_720_Ruler.png",
'bubble': "assets/play/bubble.png",
'replay': 'assets/play/replay.png',
'title': 'assets/play/multiple-choice.png',
'group': 'assets/play/group.png',
'rectangle-3': 'assets/play/rectangle-3.png',
'drop-down': 'assets/play/drop-down.png',
'combined-shape': 'assets/play/combined-shape.png',
'choice-card-typeA': 'assets/play/choice-card-a.png',
'choice-card-typeB': 'assets/play/choice-card-b.png',
'choice-card-typeC': 'assets/play/choice-card-c.png',
'choice-card-typeD': 'assets/play/choice-card-d.png',
'complete-card': 'assets/play/complete-card.png',
'header': 'assets/play/header.png',
'background': 'assets/play/background.png',
'question-image': 'assets/play/question-image.png',
'speaker-1': 'assets/play/speaker-1.png',
'correct-icon': 'assets/play/correct-icon.png',
'incorrect-icon': 'assets/play/incorrect-icon.png',
'red-circle': 'assets/play/combined-shape-red-circle.png',
'rectangle-4': 'assets/play/rectangle-4.png',
'me': 'assets/play/me.png',
'bg-240-180': 'assets/play/bg-240-180.png',
'bg-453-251': 'assets/play/bg-453-251.png',
't_right': "assets/play/right.png",
't_arrow': "assets/play/arrow.png",
'bg_500_600': "assets/play/bg_500_600.png",
'bg_1280_222': "assets/play/bg_1280_222.png",
'bg_ready': "assets/play/bg_ready.png",
'ready': "assets/play/ready.png",
'go': "assets/play/go.png"
};
// ['bg', "assets/play/bg.jpg"],
['btn_left', "assets/play/btn_left.png"],
['btn_right', "assets/play/btn_right.png"],
// ['text_bg', "assets/play/text_bg.png"],
]; const localAudios = {
'sm-back': "assets/audio/sm-back.mp3",
'sm-display': "assets/audio/sm-display.mp3",
'sm-wrong': "assets/audio/sm-wrong.mp3",
'sm-win': "assets/audio/sm-win.mp3",
'sm-in': "assets/audio/sm-in.mp3",
'sm-out': "assets/audio/sm-out.mp3",
'sm-click': "assets/audio/sm-click.mp3",
'sm-start': "assets/audio/sm-start.mp3",
'sm-correct': 'assets/audio/sm-correct.mp3',
'sm-choice-complete': 'assets/audio/sm-choice-complete.mp3',
'sm-choice-correct': 'assets/audio/sm-choice-correct.mp3',
'sm-choice-incorrect': 'assets/audio/sm-choice-error.mp3',
'sm-choice-in': 'assets/audio/sm-choice-in.mp3',
'sm-choice-show-answer': 'assets/audio/sm-choice-show-answer.mp3',
'sm-choice-timeup-0': 'assets/audio/sm-choice-timeup-0.mp3',
'sm-choice-timeup-3': 'assets/audio/sm-choice-timeup-3.mp3',
'sm-go': 'assets/audio/sm-go.mp3',
'sm-ready': 'assets/audio/sm-ready.mp3'
};
const resAudio = [ export {localImages, localAudios};
['click', "assets/play/music/click.mp3"],
];
export {res, resAudio};
import {
MySprite,
getMinScale,
ShapeRect,
tweenChange,
randomSortByArr,
Label,
showPopParticle,
moveItem,
removeItemFromArr,
rotateItem
} from "./Unit";
const myUtility = {};
// 系统缩放比例
myUtility.mapScale = 1;
// 音乐 和 图片的缓冲区
myUtility.audio = new Map();
myUtility.images = new Map();
myUtility.imagesOriginSize = new Map();
// 坐标原点 包含缩放
myUtility.originX = 0;
myUtility.originY = 0;
myUtility.setOrigin = (x, y)=>{
myUtility.originX = x;
myUtility.originY = y;
}
myUtility.getOrigin = ()=>{
return {
x: myUtility.originX,
y: myUtility.originY
}
}
// 坐标原点 包含缩放
myUtility.relativeOriginX = 0;
myUtility.relativeOriginY = 0;
myUtility.setRelativeOrigin = (x, y)=>{
myUtility.relativeOriginX = x;
myUtility.relativeOriginY = y;
}
myUtility.getRelativeOrigin = ()=>{
return {
x: myUtility.relativeOriginX,
y: myUtility.relativeOriginY
}
}
// 存放音乐和图片的地址
const audioObj = {}
const imageObj = {}
// 添加音乐
myUtility.audio.add = ( key, url ) => {
audioObj[key] = url
};
// 添加音乐
myUtility.images.add = ( key, url ) => {
imageObj[key] = url
};
// 播放音乐
myUtility.audio.playAudio = function(key, now = false, callback = null) {
const audio = myUtility.audio.get(key);
if (audio) {
if (now) {
audio.pause();
audio.currentTime = 0;
}
if (callback) {
audio.onended = () => {
callback();
};
}
audio.play();
}
}
// 异步加载图片 音频资源
myUtility.loadResources = ()=> {
const pr = [];
for(let key in imageObj){
const p = preloadImage(imageObj[key]).then(img => {
myUtility.images.set(key, img);
myUtility.imagesOriginSize.set(key, {width:img.width, height:img.height});
}).catch(err => console.log(key));
pr.push(p);
};
for(let key in audioObj){
const a = preloadAudio(audioObj[key]).then((music) => {
myUtility.audio.set(key, music);
}).catch(err => console.log(key));
pr.push(a);
};
return Promise.all(pr);
}
// 预加载图片
const preloadImage = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
}
// 预加载音频
const preloadAudio = (url) => {
return new Promise((resolve, reject) => {
const audio = new Audio();
audio.oncanplay = a => {
resolve(audio);
};
audio.onerror = () => {
reject();
};
audio.src = url;
audio.load();
});
}
// 缓存页面元素
myUtility.cartoonElementsBuffer = {}
myUtility.createCartoonElement = (key, element, width, heigth, initX, initY)=>{
myUtility.cartoonElementsBuffer[key] = {}
myUtility.cartoonElementsBuffer[key].id = key;
myUtility.cartoonElementsBuffer[key].width = width;
myUtility.cartoonElementsBuffer[key].heigth = heigth;
myUtility.cartoonElementsBuffer[key].initX = initX;
myUtility.cartoonElementsBuffer[key].initY = initY;
myUtility.cartoonElementsBuffer[key].ref = element;
return myUtility.cartoonElementsBuffer[key]
}
myUtility.getCartoonElementRef = (key)=>{
if(myUtility.cartoonElementsBuffer[key]){
return myUtility.cartoonElementsBuffer[key].ref;
}else{
return undefined
}
}
myUtility.getCartoonElement = (key)=>{
return myUtility.cartoonElementsBuffer[key]
}
myUtility.setCartoonElementPosition = (key, posi)=>{
myUtility.cartoonElementsBuffer[key].ref.x = posi.x
myUtility.cartoonElementsBuffer[key].ref.y = posi.y
myUtility.cartoonElementsBuffer[key].x = posi.x
myUtility.cartoonElementsBuffer[key].y = posi.y
}
myUtility.setCartoonElementPositionX = (key, x)=>{
myUtility.cartoonElementsBuffer[key].ref.x = x
myUtility.cartoonElementsBuffer[key].x = x
}
myUtility.setCartoonElementRelativePositionX = (key, x)=>{
myUtility.cartoonElementsBuffer[key].relativeX = x
}
myUtility.setCartoonElementPositionY = (key, y)=>{
myUtility.cartoonElementsBuffer[key].ref.y = y
myUtility.cartoonElementsBuffer[key].y = y
}
myUtility.setCartoonElementRelativePositionY = (key, y)=>{
myUtility.cartoonElementsBuffer[key].relativeY = y
}
myUtility.getCartoonElementPosition = (key)=>{
return {
x: myUtility.cartoonElementsBuffer[key].x,
y: myUtility.cartoonElementsBuffer[key].y
}
}
myUtility.getCartoonElementRelativePosition = (key)=>{
return {
x: myUtility.cartoonElementsBuffer[key].relativeX,
y: myUtility.cartoonElementsBuffer[key].relativeY
}
}
myUtility.animation = {}
myUtility.animation.move = (eleKey, distPosition, runTime, callback )=>{
tweenChange(myUtility.cartoonElementsBuffer[eleKey].ref, distPosition, runTime, ()=>{
callback && callback()
});
}
myUtility.animation.scaleChange = myUtility.animation.move;
export default myUtility
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
<!-- <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">--> <!-- <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">-->
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="icon" type="image/x-icon" href="favicon.ico">
<script type="text/javascript" src="https://staging-teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air.js"></script> <script type="text/javascript" src="https://staging-teach.cdn.ireadabc.com/h5template/h5-static-lib/js/air_online.js"></script>
</head> </head>
<body> <body>
......
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