Commit df3295f8 authored by limingzhe's avatar limingzhe

first

parent 1f535d89
......@@ -44,7 +44,7 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
@ViewChild('canvas') canvas: ElementRef;
@ViewChild('wrap') wrap: ElementRef;
@HostListener('window:resize', ['$event'])
// @HostListener('window:resize', ['$event'])
canvasWidth = 1280;
canvasHeight = 720;
......@@ -68,7 +68,7 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
images = new Map();
animationId: any;
winResizeEventStream = new Subject();
// winResizeEventStream = new Subject();
canvasLeft;
canvasTop;
......@@ -95,7 +95,7 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
onResize(event) {
this.winResizeEventStream.next();
// this.winResizeEventStream.next();
}
......@@ -655,11 +655,11 @@ export class CustomHotZoneComponent implements OnInit, OnDestroy, OnChanges {
initListener() {
this.winResizeEventStream
.pipe(debounceTime(500))
.subscribe(data => {
this.renderAfterResize();
});
// this.winResizeEventStream
// .pipe(debounceTime(500))
// .subscribe(data => {
// this.renderAfterResize();
// });
if (this.IsPC()) {
......
<div class="courseware-container d-flex">
<div class="courseware-container" #videoContainer>
<div class="gutter" style="width: 100%;">
<app-lesson-title-config
(titleUpdated)="updateTitleObjSuccess($event)"
[withIcon]="false"
[titleObj]="titleObj">
</app-lesson-title-config>
<nz-divider></nz-divider>
<div nz-col nzSpan="5" nzOffset="1" class="img-box"
*ngFor="let it of picArr; let i = index">
<span>item-{{i+1}}</span>
<div class="img-box-upload">
<app-upload-image-with-preview
[picUrl]="it.pic_url"
(imageUploaded)="onImageUploadSuccessByItem($event, it)">
</app-upload-image-with-preview>
</div>
<app-audio-recorder
[audioUrl]="it.audio_url"
(audioUploaded)="onAudioUploadSuccessByItem($event, it)"
></app-audio-recorder>
</div>
<!---->
<!--<app-custom-hot-zone-->
<!--[bgItem]="bgItem"-->
<!--[hotZoneItemArr]="hotZoneItemArr"-->
<!--(save)="saveData($event)"-->
<!--&gt;-->
<!--</app-custom-hot-zone>-->
<!--<div nz-row nzType="flex" nzAlign="middle" style="margin-top: 5vw">-->
<!--<div nz-col nzSpan="5" nzOffset="1" class="img-box"-->
<!--*ngFor="let it of hotZoneItemArr; let i = index">-->
<!--<span>item-{{i+1}}</span>-->
<!--<div class="img-box-upload">-->
<!--<app-upload-image-with-preview-->
<!--[picUrl]="it.pic_url"-->
<!--(imageUploaded)="onImageUploadSuccessByItem($event, it)">-->
<!--</app-upload-image-with-preview>-->
<!--</div>-->
<!--<app-audio-recorder-->
<!--[audioUrl]="it.audio_url"-->
<!--(audioUploaded)="onAudioUploadSuccessByItem($event, it)"-->
<!--&gt;</app-audio-recorder>-->
<!--</div>-->
<!--</div>-->
<!--<div class="col-8">-->
<!--&lt;!&ndash;crossorigin="anonymous"&ndash;&gt;-->
<!--<video class="courseware-video"-->
<!--crossorigin="anonymous"-->
<!--*ngIf="item.contentObj.video_url "-->
<!--[src]="item.contentObj.video_url | resource" controls-->
<!--(loadeddata)="videoLoaded($event,item)"-->
<!--(error)="videoError($event)"-->
<!--(seeked)="videoSeeked($event, false)"-->
<!--#videoNode ></video>-->
<!--&lt;!&ndash;&& item.contentObj.video_url.constructor.name === 'String'&ndash;&gt;-->
<!--<div *ngIf="!item.contentObj.video_url">-->
<!--<div class="p-video-box d-flex align-items-center">-->
<!--<div class="p-upload-icon">-->
<!--&lt;!&ndash;<i class="anticon anticon-caret-right"></i>&ndash;&gt;-->
<!--<i nz-icon type="caret-right" theme="outline"></i>-->
<!--<div class="m-3"></div>-->
<!--</div>-->
<!--</div>-->
<!--</div>-->
<!--</div>-->
<!--<div class="col-4">-->
<!--<app-upload-video-->
<!--(videoUploaded)="onVideoUploadSuccess($event)"-->
<!--[item]="item"-->
<!--[videoUrl]="item.contentObj.video_url"></app-upload-video>-->
<!--</div>-->
<!--</div>-->
<!--<div class="row" style="margin-top: 1rem"-->
<!--*ngIf="item.contentObj.video_id && item.contentObj.video_url && item.contentObj.video_url.constructor.name === 'String'">-->
<!--<div class="col-8">-->
<!--<button nz-button nzType="primary"-->
<!--style="margin-bottom: 1rem"-->
<!--(click)="setVideoCover()">-->
<!--Set Video Cover-->
<!--</button>-->
<!--&lt;!&ndash;crossOrigin="anonymous"&ndash;&gt;-->
<!--<img *ngIf="item.contentObj.pic_id"-->
<!--[src]="item.contentObj.pic_id | resource"-->
<!--style="width:100%;overflow: hidden;box-shadow: 0 0 20px 0px #444;"/>-->
<!--<app-upload-image-with-preview-->
<!--[picUrl]="item.contentObj.video_cover_url"-->
<!--(imageUploaded)="onCoverUploadSuccess($event)"-->
<!--[picItem]="coverImg"-->
<!--[disableUpload]="true"-->
<!--[TIP]="' '"-->
<!--[iconSize]="0"-->
<!--style="width:100%;overflow: hidden;box-shadow: 0 0 20px 0px #444;">-->
<!--</app-upload-image-with-preview>-->
<!--</div>-->
</div>
@import '../style/common_mixin';
.tw{
display: flex;
.t{
flex: 1 1 auto;
margin-right: 2rem;
}
.a{
.courseware-container {
padding: 5%;
}
}
.img-box {
margin-bottom: 1rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.aud-w{
.img-box-upload{
width: 100%;
display: flex;
justify-content: center;
margin-top: 1.5rem;
}
import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef} from '@angular/core';
import * as _ from 'lodash';
import {
ApplicationRef,
Component,
ElementRef,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
OnDestroy,
ViewChild
} from '@angular/core';
import {NzMessageDataFilled, NzMessageService} from 'ng-zorro-antd';
@Component({
// providers:[UploadImageWithPreviewComponent ],
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
// @Input()
item;
@ViewChild('videoContainer')
videoContainer: ElementRef;
@ViewChild('videoNode')
videoNode: ElementRef;
@Output()
update = new EventEmitter();
intervalId;
picArr;
// titleObj = {
// audio_url: 'http://iplayabc-courseware.oss-cn-beijing.aliyuncs.com/dev/imman/audios/d108d5d06105fda0526059a3e372f926.mp3',
// content: 'what is this?&nbsp;',
// icons: [],
// type: 'a'
// };
KEY = 'dfzx_10';
titleObj = {
audio_url: '',
content: '',
icons: [],
type: ''
};
teststr = "";
constructor(private appRef: ApplicationRef) {
constructor(private nzMessageService: NzMessageService,
private appRef: ApplicationRef) {
}
ngOnChanges() {
console.log(1, 'ngOnChanges');
// if (typeof this.item.contentObj.video_url !== 'string') {
// // this.item.contentObj.video_url = '';
// setTimeout(() => {
// this.item.contentObj.video_url = '';
// });
// }
}
ngOnInit() {
let _this = this;
(<any>window).courseware.getData(function(data){
if(data){
_this.titleObj = data;
setTimeout(() => {
_this.appRef.tick();
}, 1);
console.log(2, 'ngOnInit');
// if (typeof this.item.contentObj.video_url !== 'string') {
// // this.item.contentObj.video_url = '';
// setTimeout(() => {
// this.item.contentObj.video_url = '';
// });
// }
const getData = (<any> window).courseware.getData;
getData((data) => {
if (data) {
this.item = data;
} else {
this.item = {};
this.item.contentObj = {};
}
});
this.initDefaultData();
console.log('data:', data);
this.init();
this.refresh();
}, this.KEY);
}
ngOnChanges() {
initDefaultData() {
const picArr = this.item.contentObj.picArr;
if (!picArr) {
const picArr = [];
for (let i = 0; i < 4; i ++) {
picArr.push({
pic_url: '',
audio_url: ''
});
}
this.item.contentObj.picArr = picArr;
}
}
ngOnDestroy() {
console.log('in ngOnDestory');
}
init() {
this.picArr = this.item.contentObj.picArr || [];
this.item.contentObj.picArr = this.picArr;
}
onImageUploadSuccessByItem(e, item, id = null) {
if (id != null) {
item[id + '_pic_url'] = e.url;
} else {
item.pic_url = e.url;
}
updateTitleObjSuccess(titleObj) {
this.titleObj = titleObj;
this.save();
// this.update.emit(this.item);
// console.log('this.item: ', this.item);
}
onTitleAudioUploadSuccess(res) {
this.titleObj.audio_url = res.url;
onAudioUploadSuccessByItem(e, item, id = null) {
if (id != null) {
item[id + '_audio_url'] = e.url;
} else {
item.audio_url = e.url;
}
// this.update.emit(this.item);
this.save();
}
save() {
(<any>window).courseware.setData(this.titleObj);
(<any> window).courseware.setData(this.item, null, this.KEY);
this.refresh();
}
refresh() {
setTimeout(() => {
this.appRef.tick();
}, 1);
}
}
import TWEEN from '@tweenjs/tween.js';
import {del} from 'selenium-webdriver/http';
import construct = Reflect.construct;
class Sprite {
x = 0;
y = 0;
color = '';
radius = 0;
alive = false;
margin = 0;
angle = 0;
ctx;
constructor(ctx) {
this.ctx = ctx;
}
update($event) {
this.draw();
}
draw() {
}
}
export class MySprite extends Sprite {
_width = 0;
_height = 0;
_anchorX = 0;
_anchorY = 0;
_offX = 0;
_offY = 0;
scaleX = 1;
scaleY = 1;
_alpha = 1;
rotation = 0;
visible = true;
skewX = 0;
skewY = 0;
children = [this];
childDepandVisible = true;
childDepandAlpha = false;
img;
_z = 0;
init(imgObj = null, anchorX:number = 0.5, anchorY:number = 0.5) {
if (imgObj) {
this.img = imgObj;
this.width = this.img.width;
this.height = this.img.height;
}
this.anchorX = anchorX;
this.anchorY = anchorY;
}
update($event = null) {
if (!this.visible && this.childDepandVisible) {
return;
}
this.draw();
}
draw() {
this.ctx.save();
this.drawInit();
this.updateChildren();
this.ctx.restore();
}
drawInit() {
this.ctx.translate(this.x, this.y);
this.ctx.rotate(this.rotation * Math.PI / 180);
this.ctx.scale(this.scaleX, this.scaleY);
this.ctx.globalAlpha = this.alpha;
this.ctx.transform(1, this.skewX, this.skewY, 1, 0, 0);
}
drawSelf() {
if (this.img) {
this.ctx.drawImage(this.img, this._offX, this._offY);
}
}
updateChildren() {
if (this.children.length <= 0) { return; }
for (let i = 0; i < this.children.length; i++) {
if (this.children[i] === this) {
if (this.visible) {
this.drawSelf();
}
} else {
this.children[i].update();
}
}
}
load(url, anchorX = 0.5, anchorY = 0.5) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
}).then(img => {
this.init(img, anchorX, anchorY);
return img;
});
}
addChild(child, z = 1) {
if (this.children.indexOf(child) === -1) {
this.children.push(child);
child._z = z;
child.parent = this;
}
this.children.sort((a, b) => {
return a._z - b._z;
});
if (this.childDepandAlpha) {
child.alpha = this.alpha;
}
}
removeChild(child) {
const index = this.children.indexOf(child);
if (index !== -1) {
this.children.splice(index, 1);
}
}
removeChildren() {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i]) {
if (this.children[i] != this) {
this.children.splice(i, 1);
i --;
}
}
}
}
_changeChildAlpha(alpha) {
for (let i = 0; i < this.children.length; i++) {
if (this.children[i] != this) {
this.children[i].alpha = alpha;
}
}
}
set alpha(v) {
this._alpha = v;
if (this.childDepandAlpha) {
this._changeChildAlpha(v);
}
}
get alpha() {
return this._alpha;
}
set width(v) {
this._width = v;
this.refreshAnchorOff();
}
get width() {
return this._width;
}
set height(v) {
this._height = v;
this.refreshAnchorOff();
}
get height() {
return this._height;
}
set anchorX(value) {
this._anchorX = value;
this.refreshAnchorOff();
}
get anchorX() {
return this._anchorX;
}
set anchorY(value) {
this._anchorY = value;
this.refreshAnchorOff();
}
get anchorY() {
return this._anchorY;
}
refreshAnchorOff() {
this._offX = -this._width * this.anchorX;
this._offY = -this._height * this.anchorY;
}
setScaleXY(value) {
this.scaleX = this.scaleY = value;
}
getBoundingBox() {
const getParentData = (item) => {
let px = item.x;
let py = item.y;
let sx = item.scaleX;
let sy = item.scaleY;
const parent = item.parent;
if (parent) {
const obj = getParentData(parent);
const _x = obj.px;
const _y = obj.py;
const _sx = obj.sx;
const _sy = obj.sy;
px = _x + item.x * _sx;
py = _y + item.y * _sy;
sx *= _sx;
sy *= _sy;
}
return {px, py, sx, sy};
};
const data = getParentData(this);
const x = data.px + this._offX * Math.abs(data.sx);
const y = data.py + this._offY * Math.abs(data.sy);
const width = this.width * Math.abs(data.sx);
const height = this.height * Math.abs(data.sy);
// const x = this.x + this._offX * Math.abs(this.scaleX);
// const y = this.y + this._offY * Math.abs(this.scaleY);
// const width = this.width * Math.abs(this.scaleX);
// const height = this.height * Math.abs(this.scaleY);
return {x, y, width, height};
}
}
export class ColorSpr extends MySprite {
r = 0;
g = 0;
b = 0;
createGSCanvas(){
if (!this.img) {
return;
}
const rect = this.getBoundingBox();
if (rect.width <= 1 || rect.height <= 1) {
return;
}
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for( let i = 0; i < c.height; i++){
for( let j = 0; j < c.width; j++){
const x = (i * 4) * c.width + ( j * 4 );
const r = c.data[x];
const g = c.data[x + 1];
const b = c.data[x + 2];
c.data[x] = this.r;
c.data[x + 1] = this.g;
c.data[x + 2] = this.b;
// c.data[x] = c.data[x + 1] = c.data[x + 2] = (r + g + b) / 3 ;
// // c.data[x + 3] = 255;
}
}
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
}
drawSelf() {
super.drawSelf();
this.createGSCanvas();
}
}
export class GrayscaleSpr extends MySprite {
grayScale = 120;
createGSCanvas(){
if (!this.img) {
return;
}
const rect = this.getBoundingBox();
const c = this.ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
for( let i = 0; i < c.height; i++){
for( let j = 0; j < c.width; j++){
const x = (i * 4) * c.width + ( j * 4 );
const r = c.data[x];
const g = c.data[x + 1];
const b = c.data[x + 2];
// const a = c.data[x + 3];
c.data[x] = c.data[x + 1] = c.data[x + 2] = this.grayScale; // (r + g + b) / 3;
// c.data[x + 3] = 255;
}
}
this.ctx.putImageData(c, rect.x, rect.y, 0, 0, rect.width, rect.height);
}
drawSelf() {
super.drawSelf();
this.createGSCanvas();
}
}
export class BitMapLabel extends MySprite {
labelArr;
baseUrl;
setText(data, text) {
this.labelArr = [];
const labelArr = [];
const tmpArr = text.split('');
let totalW = 0;
let h = 0;
for (let i = 0; i < tmpArr.length; i++) {
const label = new MySprite(this.ctx);
label.init(data[tmpArr[i]], 0);
this.addChild(label);
labelArr.push(label);
totalW += label.width;
h = label.height;
}
this.width = totalW;
this.height = h;
let offX = -totalW / 2;
for (let i = 0; i < labelArr.length; i++) {
labelArr[i].x = offX;
offX += labelArr[i].width;
}
this.labelArr = labelArr;
}
}
export class Label extends MySprite {
text: String;
// fontSize:String = '40px';
fontName: String = 'Verdana';
textAlign: String = 'left';
fontSize = 40;
fontColor = '#000000';
fontWeight = 900;
maxWidth;
outline = 0;
outlineColor = '#ffffff';
_shadowFlag = false;
_shadowColor;
_shadowOffsetX;
_shadowOffsetY;
_shadowBlur;
_outlineFlag = false;
_outLineWidth;
_outLineColor;
constructor(ctx) {
super(ctx);
this.init();
}
refreshSize() {
this.ctx.save();
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
this._width = this.ctx.measureText(this.text).width;
this._height = this.fontSize;
this.refreshAnchorOff();
this.ctx.restore();
}
setMaxSize(w) {
this.maxWidth = w;
this.refreshSize();
if (this.width >= w) {
this.scaleX *= w / this.width;
this.scaleY *= w / this.width;
}
}
show(callBack = null) {
this.visible = true;
if (this.alpha >= 1) {
return;
}
const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(function() {
if (callBack) {
callBack();
}
})
.start(); // Start the tween immediately.
}
setShadow(offX = 2, offY = 2, blur = 2, color = 'rgba(0, 0, 0, 0.2)') {
this._shadowFlag = true;
this._shadowColor = color;
// 将阴影向右移动15px,向上移动10px
this._shadowOffsetX = offX;
this._shadowOffsetY = offY;
// 轻微模糊阴影
this._shadowBlur = blur;
}
setOutline(width = 5, color = '#ffffff') {
this._outlineFlag = true;
this._outLineWidth = width;
this._outLineColor = color;
}
drawText() {
// console.log('in drawText', this.text);
if (!this.text) { return; }
if (this._shadowFlag) {
this.ctx.shadowColor = this._shadowColor;
// 将阴影向右移动15px,向上移动10px
this.ctx.shadowOffsetX = this._shadowOffsetX;
this.ctx.shadowOffsetY = this._shadowOffsetY;
// 轻微模糊阴影
this.ctx.shadowBlur = this._shadowBlur;
}
this.ctx.font = `${this.fontSize}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
if (this._outlineFlag) {
this.ctx.lineWidth = this._outLineWidth;
this.ctx.strokeStyle = this._outLineColor;
this.ctx.strokeText(this.text, 0, 0);
}
this.ctx.fillStyle = this.fontColor;
if (this.outline > 0) {
this.ctx.lineWidth = this.outline;
this.ctx.strokeStyle = this.outlineColor;
this.ctx.strokeText(this.text, 0, 0);
}
this.ctx.fillText(this.text, 0, 0);
}
drawSelf() {
super.drawSelf();
this.drawText();
}
}
export class RichText extends Label {
textArr = [];
fontSizeNum = 40;
setText(text:string, words) {
let newText = text;
for (let i = 0; i < words.length; i++) {
const word = words[i];
const re = new RegExp(word, 'g');
newText = newText.replace( re, `#${word}#`);
// newText = newText.replace(word, `#${word}#`);
}
this.textArr = newText.split('#');
this.text = newText;
// this.setSize();
}
refreshSize() {
this.ctx.save();
this.ctx.font = `${this.fontSizeNum}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = this.fontWeight;
let curX = 0;
for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width;
curX += w;
}
this.width = curX;
this.height = this.fontSizeNum;
this.refreshAnchorOff();
this.ctx.restore();
}
show(callBack = null) {
// console.log(' in show ');
this.visible = true;
// this.alpha = 0;
const tween = new TWEEN.Tween(this)
.to({ alpha: 1 }, 800)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(function() {
if (callBack) {
callBack();
}
})
.start(); // Start the tween immediately.
}
drawText() {
// console.log('in drawText', this.text);
if (!this.text) { return; }
this.ctx.font = `${this.fontSizeNum}px ${this.fontName}`;
this.ctx.textAlign = this.textAlign;
this.ctx.textBaseline = 'middle';
this.ctx.fontWeight = 900;
this.ctx.lineWidth = 5;
this.ctx.strokeStyle = '#ffffff';
// this.ctx.strokeText(this.text, 0, 0);
this.ctx.fillStyle = '#000000';
// this.ctx.fillText(this.text, 0, 0);
let curX = 0;
for (let i = 0; i < this.textArr.length; i++) {
const w = this.ctx.measureText(this.textArr[i]).width;
if ((i + 1) % 2 == 0) {
this.ctx.fillStyle = '#c8171e';
} else {
this.ctx.fillStyle = '#000000';
}
this.ctx.fillText(this.textArr[i], curX, 0);
curX += w;
}
}
}
export class ShapeRect extends MySprite {
fillColor = '#FF0000';
setSize(w, h) {
this.width = w;
this.height = h;
console.log('w:', w);
console.log('h:', h);
}
drawShape() {
this.ctx.fillStyle = this.fillColor;
this.ctx.fillRect(this._offX, this._offY, this.width, this.height);
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class ShapeCircle extends MySprite {
fillColor = '#FF0000';
radius = 0;
setRadius(r) {
this.anchorX = this.anchorY = 0.5;
this.radius = r;
this.width = r * 2;
this.height = r * 2;
}
drawShape() {
this.ctx.beginPath();
this.ctx.fillStyle = this.fillColor;
this.ctx.arc(0, 0, this.radius, 0, angleToRadian(360));
this.ctx.fill();
}
drawSelf() {
super.drawSelf();
this.drawShape();
}
}
export class MyAnimation extends MySprite {
frameArr = [];
frameIndex = 0;
playFlag = false;
lastDateTime;
curDelay = 0;
loop = false;
playEndFunc;
delayPerUnit = 1;
restartFlag = false;
reverseFlag = false;
addFrameByImg(img) {
const spr = new MySprite(this.ctx);
spr.init(img);
this._refreshSize(img);
spr.visible = false;
this.addChild(spr);
this.frameArr.push(spr);
this.frameArr[this.frameIndex].visible = true;
}
addFrameByUrl(url) {
const spr = new MySprite(this.ctx);
spr.load(url).then(img => {
this._refreshSize(img);
});
spr.visible = false;
this.addChild(spr);
this.frameArr.push(spr);
this.frameArr[this.frameIndex].visible = true;
}
_refreshSize(img) {
if (this.width < img['width']) {
this.width = img['width'];
}
if (this.height < img['height']) {
this.height = img['height'];
}
}
play() {
this.playFlag = true;
this.lastDateTime = new Date().getTime();
}
stop() {
this.playFlag = false;
}
replay() {
this.restartFlag = true;
this.play();
}
reverse() {
this.reverseFlag = !this.reverseFlag;
this.frameArr.reverse();
this.frameIndex = 0;
}
showAllFrame() {
for (let i = 0; i < this.frameArr.length; i++) {
this.frameArr[i].alpha = 1;
}
}
hideAllFrame() {
for (let i = 0; i < this.frameArr.length; i++) {
this.frameArr[i].alpha = 0;
}
}
playEnd() {
this.playFlag = false;
this.curDelay = 0;
this.frameArr[this.frameIndex].visible = true;
if (this.playEndFunc) {
this.playEndFunc();
this.playEndFunc = null;
}
}
updateFrame() {
if (this.frameArr[this.frameIndex]) {
this.frameArr[this.frameIndex].visible = false;
}
this.frameIndex ++;
if (this.frameIndex >= this.frameArr.length) {
if (this.loop) {
this.frameIndex = 0;
} else if (this.restartFlag) {
this.restartFlag = false;
this.frameIndex = 0;
} else {
this.frameIndex -- ;
this.playEnd();
return;
}
}
this.frameArr[this.frameIndex].visible = true;
}
_updateDelay(delay) {
this.curDelay += delay;
if (this.curDelay < this.delayPerUnit) {
return;
}
this.curDelay -= this.delayPerUnit;
this.updateFrame();
}
_updateLastDate() {
if (!this.playFlag) { return; }
let delay = 0;
if (this.lastDateTime) {
delay = (new Date().getTime() - this.lastDateTime) / 1000;
}
this.lastDateTime = new Date().getTime();
this._updateDelay(delay);
}
update($event: any = null) {
super.update($event);
this._updateLastDate();
}
}
// --------=========== util func =============-------------
export function tweenChange(item, obj, time = 0.8, callBack = null, easing = null, update = null) {
const tween = new TWEEN.Tween(item).to(obj, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
if (update) {
tween.onUpdate( (a, b) => {
update(a, b);
});
}
tween.start();
}
export function rotateItem(item, rotation, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ rotation }, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function scaleItem(item, scale, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ scaleX: scale, scaleY: scale}, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function moveItem(item, x, y, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item).to({ x, y}, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.start();
return tween;
}
export function endShow(item, s = 1) {
item.scaleX = item.scaleY = 0;
item.alpha = 0;
const tween = new TWEEN.Tween(item)
.to({ alpha: 1, scaleX: s, scaleY: s }, 800)
.easing(TWEEN.Easing.Elastic.Out) // Use an easing function to make the animation smooth.
.onComplete(function() {
})
.start();
}
export function hideItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha == 0) {
return;
}
const tween = new TWEEN.Tween(item)
.to({alpha: 0}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(function () {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function showItem(item, time = 0.8, callBack = null, easing = null) {
if (item.alpha == 1) {
return;
}
item.visible = true;
const tween = new TWEEN.Tween(item)
.to({alpha: 1}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(function () {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function alphaItem(item, alpha, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item)
.to({alpha: alpha}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(function () {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function showStar(item, time = 0.8, callBack = null, easing = null) {
const tween = new TWEEN.Tween(item)
.to({alpha: 1, scale: 1}, time * 1000)
// .easing(TWEEN.Easing.Quadratic.Out) // Use an easing function to make the animation smooth.
.onComplete(function () {
if (callBack) {
callBack();
}
});
if (easing) {
tween.easing(easing);
}
tween.start();
}
export function randomSortByArr(arr) {
const newArr = [];
const tmpArr = arr.concat();
while (tmpArr.length > 0) {
const randomIndex = Math.floor( tmpArr.length * Math.random() );
newArr.push(tmpArr[randomIndex]);
tmpArr.splice(randomIndex, 1);
}
return newArr;
}
export function radianToAngle(radian) {
return radian * 180 / Math.PI;
// 角度 = 弧度 * 180 / Math.PI;
}
export function angleToRadian(angle) {
return angle * Math.PI / 180;
// 弧度= 角度 * Math.PI / 180;
}
export function getPosByAngle(angle, len) {
const radian = angle * Math.PI / 180;
const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len;
return {x, y};
}
export function getAngleByPos(px, py, mx, my) {
const x = Math.abs(px - mx);
const y = Math.abs(py - my);
const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
const cos = y / z;
const radina = Math.acos(cos); // 用反三角函数求弧度
let angle = Math.floor(180 / (Math.PI / radina) * 100) / 100; // 将弧度转换成角度
if(mx > px && my > py) {// 鼠标在第四象限
angle = 180 - angle;
}
if(mx === px && my > py) {// 鼠标在y轴负方向上
angle = 180;
}
if(mx > px && my === py) {// 鼠标在x轴正方向上
angle = 90;
}
if(mx < px && my > py) {// 鼠标在第三象限
angle = 180 + angle;
}
if(mx < px && my === py) {// 鼠标在x轴负方向
angle = 270;
}
if(mx < px && my < py) {// 鼠标在第二象限
angle = 360 - angle;
}
// console.log('angle: ', angle);
return angle;
}
export function removeItemFromArr(arr, item) {
const index = arr.indexOf(item);
if (index != -1) {
arr.splice(index, 1);
}
}
export function circleMove(item, x0, y0, time = 2, addR = 360, xPer = 1, yPer = 1, callBack = null, easing = null){
const r = getPosDistance(item.x, item.y, x0, y0);
let a = getAngleByPos(item.x, item.y, x0, y0);
a += 90;
const obj = {r, a};
item._circleAngle = a;
const targetA = a + addR;
const tween = new TWEEN.Tween(item).to({_circleAngle: targetA}, time * 1000);
if (callBack) {
tween.onComplete(() => {
callBack();
});
}
if (easing) {
tween.easing(easing);
}
tween.onUpdate( (item, progress) => {
// console.log(item._circleAngle);
const r = obj.r;
const a = item._circleAngle;
const x = x0 + r * xPer * Math.cos(a * Math.PI / 180);
const y = y0 + r * yPer * Math.sin(a * Math.PI / 180);
item.x = x;
item.y = y;
// obj.a ++;
});
tween.start();
}
export function getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx;
const _y = ey - sy;
const len = Math.sqrt( Math.pow(_x, 2) + Math.pow(_y, 2) );
return len;
}
// --------------- custom class --------------------
<div class="player-preview-content" [ngStyle]="{'background-color': this.data.contentObj?.titleObj?.type === 'a' ? '#fce5e9' : '#d8eefb'}">
<app-player-content-wrapper>
<div [innerHTML]="data.contentObj.titleObj.content" style="
position: absolute;z-index:99;
display: inline-block;
left: 55px;
top: 20px;
cursor: pointer" (click)="playTitleAudio()"></div>
<div class="content" style = 'position: relative;width: 100%;height: 100%;display: flex;
justify-content: center;
align-items: flex-end;'>
<div class="letter-box">
<div class="letters" >
<div class="letter" *ngFor="let a of letters; let i = index"
[ngStyle]="{top: row(i) +'%', left: (10 + (i % 13) * 6.05) +'%'}">
<div class="l-box" (click)="clickItem($event, a)">
<img [src]="'assets/all-letters/letter-imgs/'+a +'.png'" alt="">
<div style="display: none">
<audio [src]="'assets/all-letters/letter-audios/'+fromCharCode(a)+'.mp3'" preload="auto"> </audio>
</div>
</div>
</div>
</div>
</div>
<div class="show-item-content"
*ngIf="showDetailFlag"
(click)="clickBg()">
<div style="width: 50%; height: 80%; margin-top: 2rem">
<img [src]="curItemUrl" style="height: 100%; width: auto;"
(click)="clickBigItem($event)">
</div>
</div>
</div>
</app-player-content-wrapper>
<div class="game-container" #wrap>
<canvas id="canvas" #canvas></canvas>
</div>
<div style="display: none">
<audio *ngIf="data.contentObj?.titleObj?.audio_url" #audioElement
[src]="data.contentObj?.titleObj?.audio_url" preload="auto"> </audio>
</div>
@import '../style/common_mixin';
.player-preview-content {
width: 100%;
height: 100%;
background-color: white;
.lesson-header{
width: 100%;
position: absolute;
top: 0;
img{
width: 100%;
height: auto;
}
.title{
font-family: 'BerlinSansFBDemi-Bold';
color: #f5d11f;
font-size: 4vw;
font-weight: 900;
width: 15%;
height: 70%;
position: absolute;
overflow: hidden;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
line-height: 4vw;
}
}
.left-box{text-align: right;padding-right: 1rem}
.right-box{text-align: left;padding-left: 1rem}
.left-box, .right-box{
height: 100%;
position: relative;
.a, .b{
width: 30%;
height: 100%;
display: inline-block;
position: relative;
margin: 0 .5rem
}
.a{
width: 40%;
}
}
.letter-box {
//height: 100%;
position: relative;
display: inline-block;
width: 100%;
height: 100%;
//margin-top: 5%;
//margin-left: 8%;
//margin-right: 8%;
img{
max-width: 100%;
max-height: 100%;
//position: absolute;
//left: 0;
height: 100%;
}
.letters{
position: absolute;
.game-container {
width: 100%;
height: 100%;
top: 0;
left: 0;
.letter{
position: absolute;
font-weight: 600;
//width: calc(100% / 13);
text-align: center;
--cw: calc(100% / 13);
width: var(--cw);
line-height: calc( var(--cw) * 13);
font-family: LiQiangXingShu;
padding: 0 1rem;
height: 20%;
font-size: 7vmin;
}
}
}
.l-box{
cursor: pointer;
width: 100%;
height: 100%;
display: flex;
flex-direction: column-reverse;
font-weight: 900;
img{
max-width: 100%;
max-height: 100%;
width: 100%;
height: auto;
}
}
//background-image: url("/assets/listen-read-circle/bg.jpg");
background: #ffffff;
background-repeat: no-repeat;
background-size: cover;
}
#canvas {
.show-item-content {
position: absolute;
width: 100%;
height: 100%;
//background-color:rgba(255,255,255,1);
}
display: flex;
align-items: center;
justify-content:center;
}
}
//@font-face
//{
// font-family: 'BRLNSDB';
// src: url("/assets/font/BRLNSDB.TTF") format("opentype");
//}
//@font-face
//{
// font-family: 'RoundedBold';
// src: url("/assets/font/Arial Rounded Bold.otf") format("opentype");
//}
import {
Component,
Input,
OnDestroy,
OnChanges,
OnInit,
AfterViewInit, ElementRef, ViewChild,
ApplicationRef
} from '@angular/core';
import {Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener} from '@angular/core';
import {
getAngleByPos,
MySprite,
getPosByAngle,
Label,
MyAnimation,
moveItem,
randomSortByArr,
scaleItem,
rotateItem,
tweenChange,
hideItem,
showItem,
BitMapLabel,
ColorSpr,
removeItemFromArr, ShapeRect, alphaItem, circleMove, ShapeCircle
} from './Unit';
import res from './resources';
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import * as _ from 'lodash';
import TWEEN from '@tweenjs/tween.js';
import {del} from 'selenium-webdriver/http';
@Component({
selector: 'app-play',
templateUrl: './play.component.html',
styleUrls: ['./play.component.scss']
})
export class PlayComponent implements OnInit, OnDestroy, OnChanges, AfterViewInit {
@ViewChild('audioElement')
audioElement: ElementRef;
data = {
contentObj:{titleObj:{
audio_url: 'http://iplayabc-courseware.oss-cn-beijing.aliyuncs.com/dev/imman/audios/d108d5d06105fda0526059a3e372f926.mp3',
content: 'what is this?&nbsp;',
icons: [],
type: 'a'
}}
};
export class PlayComponent implements OnInit, OnDestroy {
// 数据
_data;
letters = [];
lettersAscii = {};
titleAudio = null;
showDetailFlag = false;
curItemUrl = '';
curEvt;
@Input()
set data(data) {
this._data = data;
}
get data() {
return this._data;
}
constructor(private appRef: ApplicationRef) {
@Input()
sid;
@ViewChild('canvas') canvas: ElementRef;
@ViewChild('wrap') wrap: ElementRef;
canvasWidth = 1280;
canvasHeight = 720;
canvasBaseW = 1280;
canvasBaseH = 720;
ctx;
fps = 0;
frametime = 0; // 上一帧动画的时间, 两帧时间差
mx;
my; // 点击坐标
// 资源
rawImages = new Map(res);
// 声音
bgAudio = new Audio();
successAudio = new Audio();
wrongAudio = new Audio();
rightAudio = new Audio();
titleAudio = new Audio();
images = new Map();
animationId: any;
winResizeEventStream = new Subject();
audioObj = {};
renderArr;
mapScale = 1;
canvasLeft;
canvasTop;
canTouch = true;
// -----
picArr;
itemBgArr;
hotZoneArr;
picRect;
closeBtn;
itemBg;
curSong;
KEY = 'dfzx_10';
oldFrameColorId;
curCard;
bottomCard;
picW = 370;
picH = 260;
mask;
ball;
stick;
robot;
pageW = 840;
page1;
page2;
arm1;
arm2;
centerPageArr;
pageOffX = 100;
curPic;
roleArr;
picIndex = 0;
curData;
bgTop;
topImg;
curWordArr;
wordMoveFlag;
maxScore;
bottomY;
leftScore;
rightScore;
leftScoreLabel;
rightScoreLabel;
addScoreNum = 20;
leftWin;
rightWin;
startPageArr = [];
bgArr;
rightArr;
title;
startBtn;
starArr;
wand;
light;
replayBtn;
endPageArr;
gameEndFlag;
showPetalFlag;
bg;
@HostListener('window:resize', ['$event'])
onResize(event) {
this.winResizeEventStream.next();
}
range(start, end) {
return (new Array(end - start + 1)).fill(undefined).map((_, i) => i + start);
}
ngOnInit() {
let _this = this;
(<any>window).courseware.getData(function(data){
if(data){
_this.data.contentObj.titleObj.content = data.content;
setTimeout(() => {
_this.appRef.tick();
}, 1);
const getData = (<any> window).courseware.getData;
getData((data) => {
if (data && typeof data == 'object') {
this.data = data;
} else {
this.data = {};
}
});
// const letters = _.shuffle( [...this.range(97, 122), ...this.range(65, 90)]);
[...this.range(97, 122), ...this.range(65, 90)].forEach(c => {
this.lettersAscii[c] = String.fromCharCode(c);
console.log('data:' , data);
if (!this.data.contentObj) {
this.data.contentObj = {};
}
this.initDefaultData();
this.initAudio();
this.initImg();
this.initListener();
}, this.KEY);
//
// // this.initAudio();
// this.initImg();
// this.initListener();
}
initDefaultData() {
const picArr = this.data.contentObj.picArr;
if (!picArr) {
const picArr = [];
for (let i = 0; i < 4; i ++) {
picArr.push({
pic_url: 'assets/default/item.png',
audio_url: 'assets/default/audio.mp3'
});
this.letters = _.shuffle(Object.keys(this.lettersAscii));
}
this.data.contentObj.picArr = picArr;
}
}
ngOnDestroy() {
window.cancelAnimationFrame(this.animationId);
this.bgAudio.pause();
this.gameEndFlag = true;
}
initData() {
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;
const sx = this.canvasWidth / this.canvasBaseW;
const sy = this.canvasHeight / this.canvasBaseH;
const s = Math.min(sx, sy);
this.mapScale = s;
// this.mapScale = this.canvasWidth / this.canvasBaseW;
// this.mapScale = this.canvasHeight / this.canvasBaseH;
this.renderArr = [];
console.log(' in initData', this.data);
this.canTouch = true;
this.renderArr = [];
if (!this.data.contentObj.picArr) {
this.data.contentObj.picArr = [];
}
this.picArr = this.data.contentObj.picArr;
//
// // this.picArr = randomSortByArr(this.picArr);
// this.picIndex = 0;
//
}
initAudio() {
const contentObj = this.data.contentObj;
if (!contentObj) { return; }
// const addAudio = (key) => {
// const audioUrl = contentObj[key];
// if (audioUrl) {
// const audio = new Audio();
// audio.src = audioUrl;
// audio.load();
// this.audioObj[key] = audio;
// }
// }
//
// for (let i = 0; i < 4; i ++) {
// const key = i + '_audio_url';
// addAudio(key);
// }
//
// addAudio('audio_url');
//
const addUrlToAudioObj = (audioUrl) => {
if (audioUrl) {
console.log('audioUrl:', audioUrl);
const audio = new Audio();
audio.src = audioUrl;
audio.load();
this.audioObj[audioUrl] = audio;
}
};
const arr = contentObj.picArr;
if (arr) {
console.log('arr: ', arr);
for (let i = 0; i < arr.length; i++) {
addUrlToAudioObj(arr[i].audio_url);
}
}
//
// const titleUrl = this.data.contentObj.title_audio_url;
// if (titleUrl) {
//
// this.titleAudio.src = titleUrl;
// this.titleAudio.load();
// }
// this.bgAudio.src = 'assets/bat-mail/music/bg.mp3';
// this.bgAudio.load();
// this.bgAudio.loop = true;
// this.bgAudio.volume = 0.5;
//
// this.wrongAudio.src = 'assets/common/music/wrong.mp3';
// this.wrongAudio.load();
//
// this.rightAudio.src = 'assets/common/music/right.mp3';
// this.rightAudio.load();
//
// this.successAudio.src = 'assets/magic-hat/music/finish.mp3';
// this.successAudio.load();
//
// this.successAudio.onended = () => {
// // this.showSuccessAudio();
// };
//
//
//
}
ngOnChanges(data) {
initImg() {
const contentObj = this.data.contentObj;
if (contentObj) {
const addPicUrl = (url) => {
if (url) {
this.rawImages.set(url, url);
}
};
ngAfterViewInit() {
const arr = this.data.contentObj.picArr;
if (arr) {
for (let i = 0; i < arr.length; i++) {
const picUrl = arr[i].pic_url;
if (picUrl) {
this.rawImages.set(picUrl, picUrl);
}
}
}
}
clickItem(e, a) {
// this.initFontImg();
// 预加载资源
this.loadResources().then(() => {
// this.setfontData();
this.init();
this.update();
});
this.curEvt = e;
this.curItemUrl = 'assets/all-letters/letter-detail/' + a + '.png';
this.showDetailFlag = true;
}
clickBg() {
initFontImg() {
this.showDetailFlag = false;
// const fontbaseUrlW = 'assets/mechanical/letter/';
// const fontDataW = {};
//
// let num = 97;
// for (let i = 0; i < 26; i++) {
//
// const key = String.fromCharCode(num + i); // 'a'
// const url = fontbaseUrlW + key + '.png';
//
// this.rawImages.set(url, url);
// fontDataW[key] = url;
// }
//
//
// this.fontDataW = fontDataW;
}
clickBigItem(e) {
setfontData() {
e.cancelBubble = true;
this.playLetterAudio(this.curEvt);
// for (let key in this.fontDataW) {
// this.fontDataW[key] = this.images.get(this.fontDataW[key]);
// }
}
caseFolder(c) {
let folder = 'upper';
if (c.toLowerCase() === c) {
folder = 'lower';
init() {
this.initData();
this.initCtx();
this.initView();
}
return `${folder}/${c}.png`;
initCtx() {
this.ctx = this.canvas.nativeElement.getContext('2d');
this.canvas.nativeElement.width = this.canvasWidth;
this.canvas.nativeElement.height = this.canvasHeight;
// console.log('this.ctx.canvas w: ', this.ctx.canvas.width);
// console.log('this.ctx.canvas h: ', this.ctx.canvas.height);
}
row(i) {
const r = Math.floor(i / 13);
let y = (r * 20);
switch (r) {
case 0:
case 1:
y += 13;
break;
case 2:
case 3:
y += 15;
break;
initView() {
this.initBg();
this.initPic();
// this.initItemView();
// this.initHotZone();
// this.initItemView();
}
return y ;
initItemView() {
}
lower(c) {
return c.toLowerCase();
initHotZone() {
let curBgRect;
if (this.bg) {
curBgRect = this.bg.getBoundingBox();
}
fromCharCode(c) {
return String.fromCharCode(c).toLowerCase();
let oldBgRect = this.data.contentObj.bgItem.rect;
if (!oldBgRect) {
oldBgRect = curBgRect;
}
allLetters() {
const rate = curBgRect.width / oldBgRect.width;
// this.imgArr = [];
// const arr = this.data.contentObj.imgItemArr;
this.hotZoneArr = [];
const arr = this.data.contentObj.hotZoneItemArr;
if (!arr) return;
for (let i = 0; i < arr.length; i++) {
const data = JSON.parse(JSON.stringify(arr[i]));
// const img = {pic_url: data.pic_url};
data.rect.x *= rate;
data.rect.y *= rate;
data.rect.width *= rate;
data.rect.height *= rate;
data.rect.x += curBgRect.x;
data.rect.y += curBgRect.y;
const hotZone = this.getHotZoneItem(data);
hotZone.alpha = 0;
this.hotZoneArr.push(hotZone);
// hotZone['audio'] = this.audioObj[data.audio_url];
// this.imgArr.push(img);
}
playTitleAudio() {
this.titleAudio = this.audioElement ? this.audioElement.nativeElement : null;
if (!this.titleAudio) {
return;
//
//
// const hotZoneItemArr = this.data.contentObj.hotZoneItemArr;
// if (!hotZoneItemArr) {
// return;
// }
//
// if (!this.bg) {
// return;
// }
//
// const bgRect = this.bg.getBoundingBox();
// const bgItem = this.data.contentObj.bgItem;
//
// const rate = bgRect.width / bgItem.rect.width;
//
//
// for (let i = 0; i < hotZoneItemArr.length; i++) {
//
// const tmpData = hotZoneItemArr[i];
// const shapeRect = new ShapeRect(this.ctx);
// shapeRect.anchorX = 0;
// shapeRect.anchorY = 0;
// shapeRect.setSize(tmpData.rect.width, tmpData.rect.height);
// shapeRect.setScaleXY(this.bg.scaleX);
// shapeRect.x = (bgItem.rect.x - bgRect.x + tmpData.rect.x ) / rate;
// shapeRect.y = (bgItem.rect.y - bgRect.y + tmpData.rect.y ) / rate;
//
// // shapeRect.x = tmpData.rect.x - this.bg.width / 2;
// // shapeRect.y = tmpData.rect.y - this.bg.height / 2;
// // this.bg.addChild(shapeRect);
//
// this.renderArr.push(shapeRect);
// }
}
this.titleAudio.pause();
this.titleAudio.currentTime = 0;
this.titleAudio.play();
getHotZoneItem(data) {
const saveRect = data.rect;
const item = new ShapeRect(this.ctx);
item.setSize(saveRect.width, saveRect.height);
item.x = saveRect.x ;
item.y = saveRect.y ;
item['data'] = data;
this.renderArr.push(item);
// console.log('data: ', data);
return item;
}
playLetterAudio(evt) {
const audios = document.querySelectorAll('audio');
for (let i = 0; i < audios.length; i++) {
audios[i].pause();
audios[i].currentTime = 0;
initCard() {
const card = new MySprite(this.ctx);
card.init(this.images.get(this.getFrameColor()));
card.setScaleXY(this.mapScale);
card.x = this.canvasWidth / 2;
card.y = this.canvasHeight / 2;
this.addPic(card);
this.renderArr.push(card);
this.curCard = card;
this.addBottomCard();
}
getFrameColor() {
let arr = ['1', '2', '3'];
if (this.oldFrameColorId) {
removeItemFromArr(arr, this.oldFrameColorId);
}
arr = randomSortByArr(arr);
const colorId = arr[0];
this.oldFrameColorId = colorId;
return 'frame_' + colorId;
}
addPic(card) {
const curData = this.picArr[this.picIndex];
const w = 340;
const h = 340;
const pic = new MySprite(this.ctx);
pic.init(this.images.get(curData.pic_url));
const sx = w / pic.width;
const sy = h / pic.height;
const s = Math.min(sx, sy);
pic.setScaleXY(s);
pic.x = 5;
card.addChild(pic);
card.data = curData;
this.picIndex ++;
if (this.picIndex >= this.picArr.length) {
this.picIndex = 0;
}
}
initRobot() {
const robot = new MySprite(this.ctx);
robot.init(this.images.get('robot'));
robot.setScaleXY(this.mapScale);
robot.x = this.canvasWidth / 2 - 50 * this.mapScale;
robot.y = this.canvasHeight / 2 + 50 * this.mapScale;
this.renderArr.push(robot);
this.robot = robot;
const stick = new MySprite(this.ctx);
stick.init(this.images.get('stick'));
stick.anchorY = 0.95;
stick.x = robot.width / 2 + stick.width / 2 - 5;
stick.y = -25;
robot.addChild(stick);
this.stick = stick;
const ball = new MySprite(this.ctx);
ball.init(this.images.get('ball'));
ball.x = stick.x;
ball.y = stick.y - stick.height;
robot.addChild(ball);
this.ball = ball;
const mask = new MySprite(this.ctx);
mask.init(this.images.get('mask'));
mask.x = 31;
mask.y = 2;
robot.addChild(mask);
this.mask = mask;
// const w = 800;
// const h = 260;
// const rect = new ShapeRect(this.ctx);
// rect.setSize(w, h);
// rect.anchorX = 0.5;
// rect.anchorY = 0.5;
// mask.addChild(rect);
}
initBg() {
this.bgArr = [];
const bg = new MySprite(this.ctx);
bg.init(this.images.get('bg'));
bg.x = this.canvasWidth / 2;
bg.y = this.canvasHeight / 2;
const sx = this.canvasWidth / bg.width;
const sy = this.canvasHeight / bg.height;
const s = Math.max(sx, sy);
bg.setScaleXY(s);
this.bgArr.push(bg);
this.itemBgArr = [];
const itemBgW = 459 * this.mapScale;
const itemBgH = 342 * this.mapScale;
const disW = 30 * this.mapScale;
const disH = -25 * this.mapScale;
const totalW = itemBgW * 2 + disW;
const totalH = itemBgH * 2 + disH;
const offX = this.canvasWidth / 2 - totalW / 2 + itemBgW / 2;
const offY = this.canvasHeight / 2 - totalH / 2 + itemBgH / 2 + 10 * this.mapScale;
for (let i = 0; i < 2; i ++) {
for (let j = 0; j < 2; j++) {
const itemBg = new MySprite(this.ctx);
itemBg.init(this.images.get('item_bg'));
itemBg.x = offX + (itemBgW + disW) * j;
itemBg.y = offY + (itemBgH + disH) * i;
itemBg.setScaleXY(this.mapScale);
this.renderArr.push(itemBg);
this.itemBgArr.push(itemBg);
}
}
const a = evt.target.parentNode.querySelector('audio');
// a.play();
const playPromise = a.play();
if (playPromise !== undefined) {
playPromise.then(_ => {
// Automatic playback started!
// Show playing UI.
console.log(1, _)
})
.catch(error => {
// Auto-play was prevented
// Show paused UI.
console.log(2, error)
});
}
resetArm() {
this.arm1.page1.removeChildren();
this.arm1.page2.removeChildren();
this.arm2.page1.removeChildren();
this.arm2.page2.removeChildren();
this.arm1.x = this.arm1.baseX;
this.arm1.y = this.arm1.baseY;
this.arm2.x = this.arm2.baseX;
this.arm2.y = this.arm2.baseY;
this.arm1.page1.visible = true;
this.arm2.page1.visible = true;
this.arm1.page2.visible = false;
this.arm2.page2.visible = false;
this.picIndex ++ ;
if (this.picIndex >= this.picArr.length) {
this.picIndex = 0;
this.picArr = randomSortByArr(this.picArr);
}
this.setPagePoint();
this.initPic();
}
initPic() {
const w = 370; // * this.mapScale;
const h = 260;
const itemBgArr = this.itemBgArr;
// console.log('picArr:', this.picArr);
for (let i = 0; i < itemBgArr.length; i++) {
const itemBg = itemBgArr[i];
const picData = this.picArr[i];
if (picData) {
const picUrl = picData.pic_url;
// console.log('pirUrl: ', picUrl);
const pic = new MySprite(this.ctx);
pic.init(this.images.get(picUrl));
const sx = w / pic.width;
const sy = h / pic.height;
const s = Math.min(sx, sy);
pic.setScaleXY(s);
pic.x = -1;
pic.y = -9;
itemBg.addChild(pic);
itemBg['pic'] = pic;
}
const iconKey = 'icon_' + (i + 1);
const icon = new MySprite(this.ctx);
icon.init(this.images.get(iconKey));
icon.x = - itemBg.width / 2 + 40;
icon.y = - itemBg.height / 2 + 40;
itemBg.addChild(icon);
}
}
initArm() {
const pageOffX = this.pageOffX;
const arm1 = new MySprite(this.ctx);
arm1.init(this.images.get('arm_1_1'), 0, 1);
arm1.setScaleXY(this.mapScale);
arm1.x = - arm1.width * arm1.scaleX - this.pageW / 2 * this.mapScale;
arm1.y = this.canvasHeight + 60 * this.mapScale;
this.renderArr.push(arm1);
const page1 = new MySprite(this.ctx);
page1.init(this.images.get('page_1'), 0);
page1.x = arm1.width - pageOffX;
page1.y = - arm1.height + 80;
arm1.addChild(page1);
page1.alpha = 1;
const page1_2 = new MySprite(this.ctx);
page1_2.init(this.images.get('page_1_2'), 0);
page1_2.x = page1.x;
page1_2.y = page1.y;
page1_2.visible = false;
arm1.addChild(page1_2);
arm1['page1'] = page1;
arm1['page2'] = page1_2;
arm1['baseX'] = arm1.x;
arm1['baseY'] = arm1.y;
const finger = new MySprite(this.ctx);
finger.init(this.images.get('finger_1_1'), 0, 1);
arm1.addChild(finger);
const arm2 = new MySprite(this.ctx);
arm2.init(this.images.get('arm_2_1'), 1, 1);
arm2.setScaleXY(this.mapScale);
arm2.x = this.canvasWidth + arm2.width * arm2.scaleX + this.pageW / 2 * this.mapScale;
arm2.y = arm1.y;
this.renderArr.push(arm2);
const page2 = new MySprite(this.ctx);
page2.init(this.images.get('page_2'), 1);
page2.x = -arm2.width + pageOffX;
page2.y = - arm2.height + 80;
page2.alpha = 1;
arm2.addChild(page2);
const page2_2 = new MySprite(this.ctx);
page2_2.init(this.images.get('page_2_2'), 1);
page2_2.x = page2.x;
page2_2.y = page2.y;
page2_2.visible = false;
arm2.addChild(page2_2);
arm2['baseX'] = arm2.x;
arm2['baseY'] = arm2.y;
arm2['page1'] = page2;
arm2['page2'] = page2_2;
const finger2 = new MySprite(this.ctx);
finger2.init(this.images.get('finger_2_1'), 1, 1);
arm2.addChild(finger2);
const offX = this.canvasWidth / 2 - this.pageW / 2 * this.mapScale;
const tx = offX - (arm1.width) * arm1.scaleX + pageOffX * arm1.scaleX;
// moveItem(arm1, tx, arm1.y);
//
// moveItem(arm2, this.canvasWidth - tx, arm2.y);
this.page1 = page1;
this.page2 = page2;
this.arm1 = arm1;
this.arm2 = arm2;
}
setPagePoint() {
const page1 = this.page1;
const page2 = this.page2;
const curData = this.picArr[this.picIndex];
console.log('this.picArr: ', this.picArr);
console.log('curData: ', curData);
if (!curData) {
return;
}
const wordArr1 = curData.wordArr_1;
const wordArr2 = curData.wordArr_2;
const centerW = 60;
const edge = 20;
const maxW = page1.width - (centerW + edge * 2);
let num = wordArr1.length;
let disW = 20;
let circleW = 68;
let totalW = edge * 2 + circleW * num + disW * (num - 1);
let s = 1;
if (totalW >= maxW) {
s = maxW / totalW;
totalW = maxW;
}
disW *= s;
circleW *= s;
let offX = (maxW - totalW) / 2 + edge + circleW / 2;
// const disW = (w - circleW * 3) / 4;
// const offX = disW + circleW / 2;
for (let i = 0; i < wordArr1.length; i++) {
const tmpData = wordArr1[i];
let color = 'green';
if (tmpData.color) {
color = tmpData.color;
}
const point = new MySprite(this.ctx);
const key = 'point_' + color;
point.init(this.images.get(key));
point.setScaleXY(s);
point.x = offX + i * (circleW + disW);
page1.addChild(point);
}
num = wordArr2.length;
disW = 20;
circleW = 68;
totalW = edge * 2 + circleW * num + disW * (num - 1);
s = 1;
if (totalW >= maxW) {
s = maxW / totalW;
totalW = maxW;
}
disW *= s;
circleW *= s;
offX = (maxW - totalW) / 2 + edge + circleW / 2;
for (let i = 0; i < wordArr2.length; i++) {
const tmpData = wordArr2[i];
let color = 'green';
if (tmpData.color) {
color = tmpData.color;
}
const point = new MySprite(this.ctx);
const key = 'point_' + color;
point.init(this.images.get(key));
point.setScaleXY(s);
point.x = (offX + centerW - page2.width) + i * (circleW + disW);
page2.addChild(point);
}
}
initCenterPage() {
this.centerPageArr = [];
const offX = this.canvasWidth / 2 - this.pageW / 2 * this.mapScale;
const tx = offX - (this.arm1.width) * this.arm1.scaleX + this.pageOffX * this.arm1.scaleX;
const arm1_2 = new MySprite(this.ctx);
arm1_2.init(this.images.get('arm_1_2'), 0, 1);
arm1_2.setScaleXY(this.mapScale);
arm1_2.x = tx;
arm1_2.y = this.arm1.y;
// arm1_2.visible = false;
this.centerPageArr.push(arm1_2);
const finger = new MySprite(this.ctx);
finger.init(this.images.get('finger_1_2'), 0, 1);
arm1_2.addChild(finger, -2);
const arm2_2 = new MySprite(this.ctx);
arm2_2.init(this.images.get('arm_2_2'), 1, 1);
arm2_2.setScaleXY(this.mapScale);
arm2_2.x = this.canvasWidth - tx;
arm2_2.y = this.arm2.y;
// arm2_2.visible = false;
this.centerPageArr.push(arm2_2);
const finger2 = new MySprite(this.ctx);
finger2.init(this.images.get('finger_2_2'), 1, 1);
arm2_2.addChild(finger2, -2);
const centerPage = new MySprite(this.ctx);
centerPage.init(this.images.get('center_page'), 0);
centerPage.x = this.page1.x;
centerPage.y = this.page1.y;
arm1_2.addChild(centerPage, -1);
this.hideArr(this.centerPageArr);
// this.hideArr(this.centerPageArr);
}
initStartPage() {
this.starArr = [];
const maskLayer = new ShapeRect(this.ctx);
maskLayer.init(this.images.get(''));
maskLayer.setSize(this.canvasWidth, this.canvasHeight);
maskLayer.x = this.canvasWidth / 2;
maskLayer.y = this.canvasHeight / 2;
maskLayer.fillColor = '#000000';
maskLayer.alpha = 0.8;
this.startPageArr.push(maskLayer);
const startBtn = new MySprite(this.ctx);
startBtn.init(this.images.get('start_btn'));
startBtn.x = this.canvasWidth / 2;
startBtn.y = this.canvasHeight / 5 * 3;
startBtn.setScaleXY(this.mapScale);
this.startPageArr.push(startBtn);
this.startBtn = startBtn;
}
initEndPage() {
const maskLayer = new ShapeRect(this.ctx);
maskLayer.init(this.images.get(''));
maskLayer.setSize(this.canvasWidth, this.canvasHeight);
maskLayer.x = this.canvasWidth / 2;
maskLayer.y = this.canvasHeight / 2;
maskLayer.fillColor = '#000000';
maskLayer.alpha = 0.8;
this.endPageArr.push(maskLayer);
const leftWin = new MySprite(this.ctx);
leftWin.init(this.images.get('left_win'));
leftWin.x = this.canvasWidth / 2;
leftWin.y = this.canvasHeight / 2.5;
leftWin.setScaleXY(this.mapScale);
this.endPageArr.push(leftWin);
const rightWin = new MySprite(this.ctx);
rightWin.init(this.images.get('right_win'));
rightWin.x = this.canvasWidth / 2;
rightWin.y = this.canvasHeight / 2.5;
rightWin.setScaleXY(this.mapScale);
this.endPageArr.push(rightWin);
this.leftWin = leftWin;
this.rightWin = rightWin;
// const light = new MySprite(this.ctx);
// light.init(this.images.get('light_png'));
// light.x = this.canvasWidth / 2;
// light.y = this.canvasHeight / 5 * 2;
// light.setScaleXY(this.mapScale);
// this.endPageArr.push(light);
// this.light = light;
//
// const hand = new MySprite(this.ctx);
// hand.init(this.images.get('hand_png'));
// hand.x = this.canvasWidth / 2;
// hand.y = light.y;
// hand.setScaleXY(this.mapScale);
// this.endPageArr.push(hand);
// this.hand = hand;
const replayBtn = new MySprite(this.ctx);
replayBtn.init(this.images.get('replay_btn'));
replayBtn.x = this.canvasWidth / 2;
replayBtn.y = this.canvasHeight / 5 * 3.5;
replayBtn.setScaleXY(this.mapScale);
this.endPageArr.push(replayBtn);
this.replayBtn = replayBtn;
this.hideArr(this.endPageArr);
// const lightAction = () => {
// light.rotation = 0;
// rotateItem(light, 360, 10, () => {
// lightAction();
// });
// };
//
// lightAction();
}
initScore() {
const addLabelShadow = (label) => {
const labelShadow = new Label(this.ctx);
labelShadow.init();
labelShadow.text = label.text;
labelShadow.fontSize = label.fontSize;
labelShadow.fontName = label.fontName;
labelShadow.fontColor = '#e4688f';
labelShadow.textAlign = 'center';
labelShadow.y = 3;
labelShadow.setShadow(0, 2, 2, 'rgba(154, 23, 58, 0.5)');
label.addChild(labelShadow, -1);
label.shadowLabel = labelShadow;
};
const labelLeft = new Label(this.ctx);
labelLeft.init();
labelLeft.text = '0';
labelLeft.fontSize = 60;
labelLeft.fontName = 'BRLNSDB';
labelLeft.fontColor = '#fef9ff';
labelLeft.textAlign = 'center';
labelLeft.x = - this.bgTop.width / 4;
labelLeft.y = this.bgTop.height / 5;
labelLeft.refreshSize();
addLabelShadow(labelLeft);
this.bgTop.addChild(labelLeft);
this.leftScoreLabel = labelLeft;
const labelRight = new Label(this.ctx);
labelRight.init();
labelRight.text = '0';
labelRight.fontSize = 60;
labelRight.fontName = 'BRLNSDB';
labelRight.fontColor = '#fef9ff';
labelRight.textAlign = 'center';
labelRight.x = this.bgTop.width / 4;
labelRight.y = this.bgTop.height / 5;
labelRight.refreshSize();
addLabelShadow(labelRight);
this.bgTop.addChild(labelRight);
this.rightScoreLabel = labelRight;
// console.log('label.width: ', label.width);
}
showEndPage() {
this.showArr(this.endPageArr);
this.canTouch = true;
this.gameEndFlag = true;
this.showEndPatal();
this.successAudio.play();
if (this.leftScore >= this.maxScore) {
this.rightWin.visible = false;
} else {
this.leftWin.visible = false;
}
}
showEndPatal() {
this.showPetalFlag = true;
this.addPetal();
}
addPetal() {
if (!this.showPetalFlag) {
return;
}
const petal = this.getPetal();
this.endPageArr.push(petal);
moveItem(petal, petal.x, this.canvasHeight + petal.height * petal.scaleY, petal['time'], () => {
removeItemFromArr(this.endPageArr, petal);
});
rotateItem(petal, petal['tr'], petal['time']);
setTimeout(() => {
this.addPetal();
}, 100);
}
getPetal() {
const petal = new MySprite(this.ctx);
const id = Math.ceil( Math.random() * 3 );
petal.init(this.images.get('petal_' + id));
const randomS = (Math.random() * 0.4 + 0.6) * this.mapScale;
petal.setScaleXY(randomS);
const randomR = Math.random() * 360;
petal.rotation = randomR;
const randomX = Math.random() * this.canvasWidth;
petal.x = randomX;
petal.y = -petal.height / 2 * petal.scaleY;
const randomT = 2 + Math.random() * 5;
petal['time'] = randomT;
let randomTR = 360 * Math.random(); // - 180;
if (Math.random() < 0.5) { randomTR *= -1; }
petal['tr'] = randomTR;
return petal;
}
gameEnd() {
this.showEndPage();
}
mapDown(event) {
if (!this.canTouch) {
return;
}
let arr = this.itemBgArr;
for (let i = 0; i < arr.length; i ++) {
const itemBg = arr[i];
if (this.checkClickTarget(itemBg.pic)) {
this.clickItem(i);
return;
}
}
}
clickItem(index) {
const curData = this.picArr[index];
console.log("curData: ", curData);
const audio = this.audioObj[curData.audio_url];
if (audio) {
audio.play();
}
}
changeCard() {
this.canTouch = false;
const x = this.canvasWidth * 1.5;
const y = this.canvasHeight * - 0.7;
moveItem(this.curCard, x, y, 1, () => {
// this.canTouch = true;
}, TWEEN.Easing.Sinusoidal.Out);
rotateItem(this.curCard, 150);
this.bottomCard.visible = true;
scaleItem(this.bottomCard, this.mapScale, 0.6, () => {
this.canTouch = true;
}, TWEEN.Easing.Elastic.Out);
this.curCard = this.bottomCard;
this.addBottomCard();
}
addBottomCard() {
const bottomCard = new MySprite(this.ctx);
bottomCard.init(this.images.get(this.getFrameColor()));
bottomCard.setScaleXY(this.mapScale * 0.95);
bottomCard.x = this.canvasWidth / 2;
bottomCard.y = this.canvasHeight / 2;
bottomCard.visible = false;
this.addPic(bottomCard);
this.renderArr.unshift(bottomCard);
this.bottomCard = bottomCard;
}
moveArm1() {
this.canTouch = false;
const arm1 = this.arm1;
const offX = this.canvasWidth / 2 - this.pageW / 2 * this.mapScale;
const tx = offX - (arm1.width) * arm1.scaleX + this.pageOffX * arm1.scaleX;
moveItem(this.arm1, tx, arm1.y, 0.8, () => {
this.canTouch = true;
this.clickLeft();
} );
}
moveArm2() {
const arm1 = this.arm1;
const arm2 = this.arm2;
const offX = this.canvasWidth / 2 - this.pageW / 2 * this.mapScale;
const tx = offX - (arm1.width) * arm1.scaleX + this.pageOffX * arm1.scaleX;
this.canTouch = false;
moveItem(arm2, this.canvasWidth - tx, arm2.y, 0.8, () => {
this.canTouch = true;
this.clickRight();
} );
}
clickTitle() {
this.titleAudio.play();
}
clickEmpty() {
this.moveDown();
}
clickBall() {
// console.log('in clickBall');
this.canTouch = false;
const down = () => {
const targetY = this.stick.y + this.stick.height;
tweenChange(this.ball, {y: targetY}, 0.8, () => {
up();
}, TWEEN.Easing.Quadratic.In, () => {
this.stick.scaleY = (this.stick.y - this.ball.y) / this.stick.height;
});
if (this.curPic) {
hideItem(this.curPic, 0.7);
showItem(this.mask, 0.7);
}
};
const up = () => {
const targetY = this.stick.y - this.stick.height;
tweenChange(this.ball, {y: targetY}, 0.8, () => {
this.canTouch = true;
}, TWEEN.Easing.Quadratic.Out, () => {
this.stick.scaleY = (this.stick.y - this.ball.y) / this.stick.height;
});
this.showPic();
};
down();
}
showPic() {
this.mask.removeChildren();
const data = this.picArr[this.picIndex];
this.curData = data;
const curPic = new MySprite(this.ctx);
curPic.init(this.images.get(data.pic_url));
const sx = this.picW / curPic.width;
const sy = this.picH / curPic.height;
const s = Math.min(sx, sy);
curPic.setScaleXY(s);
this.robot.addChild(curPic);
curPic.x = this.mask.x;
curPic.y = this.mask.y;
this.curPic = curPic;
curPic.alpha = 0;
showItem(curPic);
hideItem(this.mask);
this.picIndex ++;
if (this.picIndex >= this.picArr.length) {
this.picIndex = 0;
}
}
clickPic() {
// console.log('in clickPic');
const curData = this.curData;
const audio = this.audioObj[curData.audio_url];
if (audio) {
audio.play();
}
}
clickLeft() {
const curData = this.picArr[this.picIndex];
const audio = this.audioObj[curData.word_1_audio_url];
if (audio) {
audio.play();
}
}
clickRight() {
const curData = this.picArr[this.picIndex];
const audio = this.audioObj[curData.word_2_audio_url];
if (audio) {
audio.play();
}
}
clickCenter() {
console.log(' in clickCenter');
this.canTouch = false;
this.arm1.visible = false;
this.arm2.visible = false;
this.showArr(this.centerPageArr);
setTimeout(() => {
this.arm1.visible = true;
this.arm2.visible = true;
this.hideArr(this.centerPageArr);
this.arm1.page1.visible = false;
this.arm1.page2.visible = true;
this.arm2.page1.visible = false;
this.arm2.page2.visible = true;
this.canTouch = true;
}, 0.25 * 1000);
// this.arm1.centerSpr.visible = true;
// this.arm1.centerSpr.x = this.arm1.x;
// this.arm1.centerSpr.y = this.arm1.y;
}
mapMove(event) {
}
mapUp(event) {
}
moveDown() {
this.canTouch = false;
const data = {y: this.arm1.y};
const tween = tweenChange(data, {y: this.arm1.y + this.canvasHeight}, 1,
() => {
this.canTouch = true;
this.resetArm();
},
TWEEN.Easing.Quadratic.In,
(item, progress) => {
this.arm1.y = item.y;
this.arm2.y = item.y;
});
}
update() {
this.animationId = window.requestAnimationFrame(this.update.bind(this));
// 清除画布内容
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
TWEEN.update();
// this.updateWordArr();
//
this.updateArr(this.bgArr);
this.updateArr(this.renderArr);
}
updateItem(item) {
if (item) {
item.update();
}
}
updateArr(arr) {
if (!arr) {
return;
}
for (let i = 0; i < arr.length; i++) {
arr[i].update(this);
}
}
initListener() {
this.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.mx = event.offsetX;
this.my = event.offsetY;
};
} else {
this.canvas.nativeElement.addEventListener('touchstart', (event) => {
setMxMyByTouch(event);
this.mapDown(event);
});
this.canvas.nativeElement.addEventListener('touchmove', (event) => {
setMxMyByTouch(event);
this.mapMove(event);
});
this.canvas.nativeElement.addEventListener('touchend', (event) => {
setMxMyByTouch(event);
this.mapUp(event);
});
this.canvas.nativeElement.addEventListener('touchcancel', (event) => {
setMxMyByTouch(event);
this.mapUp(event);
});
const setMxMyByTouch = (event) => {
// console.log('in setMxMyByTouch', event);
if (event.touches.length <= 0) {
return;
}
if (this.canvasLeft == null) {
setParentOffset();
}
this.mx = event.touches[0].pageX - this.canvasLeft;
this.my = event.touches[0].pageY - this.canvasTop;
};
const setParentOffset = () => {
const rect = this.canvas.nativeElement.getBoundingClientRect();
this.canvasLeft = rect.left;
this.canvasTop = rect.top;
};
}
}
showArr(arr) {
if (!arr) {
return;
}
for (let i = 0; i < arr.length; i++) {
arr[i].visible = true;
}
}
hideArr(arr) {
if (!arr) {
return;
}
for (let i = 0; i < arr.length; i++) {
arr[i].visible = false;
}
}
IsPC() {
if (window['ELECTRON']) {
return false; // 封装客户端标记
}
if (document.body.ontouchmove !== undefined && document.body.ontouchmove !== undefined) {
return false;
} else {
return true;
}
}
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);
});
return Promise.all(pr);
}
preload(url) {
return new Promise((resolve, reject) => {
const img = new Image();
// img.crossOrigin = "anonymous";
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
}
renderAfterResize() {
this.canvasWidth = this.wrap.nativeElement.clientWidth;
this.canvasHeight = this.wrap.nativeElement.clientHeight;
this.init();
}
checkClickTarget(target) {
const rect = target.getBoundingBox();
if (this.checkPointInRect(this.mx, this.my, rect)) {
return true;
}
return false;
}
getWorlRect(target) {
let rect = target.getBoundingBox();
if (target.parent) {
const pRect = this.getWorlRect(target.parent);
rect.x += pRect.x;
rect.y += pRect.y;
}
return rect;
}
checkPointInRect(x, y, rect) {
if (x >= rect.x && x <= rect.x + rect.width) {
if (y >= rect.y && y <= rect.y + rect.height) {
return true;
}
}
return false;
}
getPosByAngle(angle, len) {
const radian = angle * Math.PI / 180;
const x = Math.sin(radian) * len;
const y = Math.cos(radian) * len;
return {x, y};
}
getPosDistance(sx, sy, ex, ey) {
const _x = ex - sx;
const _y = ey - sy;
const len = Math.sqrt( Math.pow(_x, 2) + Math.pow(_y, 2) );
return len;
}
}
const res = [
['bg', "assets/play/bg.jpg"],
['item_bg', "assets/play/item_bg.png"],
['icon_1', "assets/play/icon_1.png"],
['icon_2', "assets/play/icon_2.png"],
['icon_3', "assets/play/icon_3.png"],
['icon_4', "assets/play/icon_4.png"],
['default_item', "assets/default/item.jpg"],
];
export default res;
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment