export function observer(
obj: any,
callback: Function,
pointer: any
): ProxyConstructor {
return new Proxy<ProxyConstructor>(obj, {
set(target, property, value, reciever): boolean {
if (target[property] !== value) callback.call(pointer, value);
Reflect.set(target, property, value, reciever);
return true;
},
});
}
export function loadRemote(path: string): Promise<any> {
return new Promise<any>((resolve, reject) => {
cc.assetManager.loadRemote(path, (error, asset) => {
if (error) reject(error);
resolve(asset);
});
});
}
export function loadRes(path: string): Promise<any> {
return new Promise<any>((resolve, reject) => {
cc.resources.load(path, (error, asset) => {
if (error) reject(error);
resolve(asset);
});
});
}
export function delay(time: number): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
setTimeout(() => {
resolve(true);
}, time);
});
}
export function randomNumBoth(Min: number, Max: number): number {
let Range: number = Max - Min;
let Rand: number = Math.random();
let num: number = Min + Math.round(Rand * Range);
return num;
}
export function manyToOne(arr: Array<any>): any {
let key = Math.floor(Math.random() * arr.length);
let val = arr[key];
return val;
}
export function deepClone(obj: any): any {
if (typeof obj !== "object" || obj == null) {
return obj;
}
let result = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}
export const timeRemainingToday = (): number => {
const today = new Date();
const tomorrowNow = new Date(today);
tomorrowNow.setDate(today.getDate() + 1);
const tomorrow = new Date(
tomorrowNow.getFullYear(),
tomorrowNow.getMonth(),
tomorrowNow.getDate()
);
return tomorrow.getTime() - today.getTime();
};
export const encode = (data) =>
window.btoa(encodeURIComponent(JSON.stringify(data)));
export const decode = (data) =>
JSON.parse(decodeURIComponent(window.atob(data)));
export function getQueryVariable(variable: string): string {
const query = window.location.search.substring(1);
const vars = query.split("&");
for (let i = 0; i < vars.length; i++) {
const pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return "";
}
export const storage = {
set(key, value) {
localStorage.setItem(key, encode(value));
},
get(key) {
let data = localStorage.getItem(key);
if (data != null && data != "") {
data = decode(data);
return data;
} else {
return null;
}
},
remove(key) {
localStorage.removeItem(key);
},
};
export function isMobile() {
return !!navigator.userAgent.match(
/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i
);
}
export function getBase64Image(img) {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
let dataURL = canvas.toDataURL("image/" + ext);
return dataURL;
}
export function getBase64ImageByUrl(src) {
return new Promise<string>((resolve, reject) => {
let image = new Image();
image.crossOrigin = "";
image.src = src;
image.onload = function () {
let base64 = getBase64Image(image);
resolve(base64);
};
});
}
export function downloadIamge(imgsrc, name) {
let image = new Image();
image.setAttribute("crossOrigin", "anonymous");
image.onload = function () {
let canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
let context = canvas.getContext("2d");
context.drawImage(image, 0, 0, image.width, image.height);
let url = canvas.toDataURL("image/png");
let a = document.createElement("a");
let event = new MouseEvent("click");
a.download = name || "photo";
a.href = url;
a.dispatchEvent(event);
};
image.src = imgsrc;
}
export function screenshot(node: cc.Node) {
return new Promise<string>((resolve, reject) => {
let nodeCamera = new cc.Node();
nodeCamera.parent = cc.find("Canvas");
let camera = nodeCamera.addComponent(cc.Camera);
let position = node.getPosition();
let width = node.width * node.scaleX;
let height = node.height * node.scaleY;
camera.alignWithScreen = false;
camera.ortho = true;
camera.orthoSize = height / 2;
let texture = new cc.RenderTexture();
texture.initWithSize(
width,
height,
cc.game["_renderContext"].STENCIL_INDEX8
);
camera.targetTexture = texture;
node.setPosition(cc.Vec2.ZERO);
camera.render(node);
node.setPosition(position);
let data = texture.readPixels();
let canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
let ctx = canvas.getContext("2d");
let rowBytes = width * 4;
for (let row = 0; row < height; row++) {
let srow = height - 1 - row;
let imageData = ctx.createImageData(width, 1);
let start = srow * width * 4;
for (let i = 0; i < rowBytes; i++) {
imageData.data[i] = data[start + i];
}
ctx.putImageData(imageData, 0, row);
}
let dataURL = canvas.toDataURL("image/jpeg");
nodeCamera.destroy();
resolve(dataURL);
});
}
export function screenshotSpriteFrame(node: cc.Node) {
return new Promise<cc.SpriteFrame>(async (resolve, reject) => {
const dataURL = await screenshot(node);
let img = document.createElement("img");
img.src = dataURL;
let texture2D = new cc.Texture2D();
texture2D.initWithElement(img);
let spriteFrame = new cc.SpriteFrame();
spriteFrame.setTexture(texture2D);
resolve(spriteFrame);
});
}
export function renderNode(nodeCapture: cc.Node) {
return new Promise<string>((resolve, reject) => {
let nodeCamera = new cc.Node();
nodeCamera.parent = cc.find("Canvas");
let camera = nodeCamera.addComponent(cc.Camera);
let position = nodeCapture.getPosition();
let width = nodeCapture.width * nodeCapture.scaleX;
let height = nodeCapture.height * nodeCapture.scaleY;
camera.alignWithScreen = false;
camera.ortho = true;
camera.orthoSize = height / 2;
let texture = new cc.RenderTexture();
texture.initWithSize(
width,
height,
cc.RenderTexture.DepthStencilFormat.RB_FMT_S8
);
camera.targetTexture = texture;
let canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
let ctx = canvas.getContext("2d");
nodeCapture.setPosition(cc.Vec2.ZERO);
camera.render(nodeCapture);
nodeCapture.setPosition(position);
let data = texture.readPixels();
let rowBytes = width * 4;
for (let row = 0; row < height; row++) {
let srow = height - 1 - row;
let imageData = ctx.createImageData(width, 1);
let start = srow * width * 4;
for (let i = 0; i < rowBytes; i++) {
imageData.data[i] = data[start + i];
}
ctx.putImageData(imageData, 0, row);
}
let dataURL = canvas.toDataURL("image/png");
let img = document.createElement("img");
img.src = dataURL;
nodeCamera.destroy();
let texture2D = new cc.Texture2D();
texture2D.initWithElement(img);
let spriteFrame = new cc.SpriteFrame();
spriteFrame.setTexture(texture2D);
let node = new cc.Node();
let sprite = node.addComponent(cc.Sprite);
sprite.spriteFrame = spriteFrame;
resolve(dataURL);
});
}
export function screenNode(
nd: cc.Node,
orthoSize: number = 750,
w: number = 750,
h: number = 1464
) {
let node = nd;
let camera = node?.getComponent(cc.Camera);
if (!camera) {
camera = node.addComponent(cc.Camera);
}
let texture = new cc.RenderTexture();
camera.alignWithScreen = false;
texture.initWithSize(w, h, cc.RenderTexture.DepthStencilFormat.RB_FMT_S8);
camera.targetTexture = texture;
camera.orthoSize = orthoSize * node.anchorX * 0.975;
camera.render();
let data = texture.readPixels();
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = texture.width;
canvas.height = texture.height;
let width = texture.width;
let height = texture.height;
let rowBytes = width * 4;
for (let row = 0; row < height; row++) {
let srow = height - 1 - row;
let imageData = ctx.createImageData(width, 1);
let start = srow * width * 4;
for (let i = 0; i < rowBytes; i++) {
imageData.data[i] = data[start + i];
}
ctx.putImageData(imageData, 0, row);
}
let dataURL = canvas.toDataURL("image/jpeg");
return dataURL;
}
export function captureNode(nodeCapture: cc.Node) {
return new Promise<cc.SpriteFrame>((resolve, reject) => {
let nodeCamera = new cc.Node();
nodeCamera.parent = cc.find("Canvas");
let camera = nodeCamera.addComponent(cc.Camera);
let width = nodeCapture.width;
let height = nodeCapture.height;
let texture = new cc.RenderTexture();
texture.initWithSize(
cc.visibleRect.width,
cc.visibleRect.height,
cc.RenderTexture.DepthStencilFormat.RB_FMT_S8
);
camera.targetTexture = texture;
let canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
let ctx = canvas.getContext("2d");
camera.render();
let size = nodeCapture.getContentSize();
let pixels = new Uint8Array(size.width * size.height * 4);
let x = texture.width / 2 - nodeCapture.width / 2;
let y = texture.height / 2 - nodeCapture.height / 2;
let w = nodeCapture.width;
let h = nodeCapture.height;
let data = texture.readPixels(pixels, x, y, w, h);
let rowBytes = width * 4;
for (let row = 0; row < height; row++) {
let srow = height - 1 - row;
let imageData = ctx.createImageData(width, 1);
let start = srow * width * 4;
for (let i = 0; i < rowBytes; i++) {
imageData.data[i] = data[start + i];
}
ctx.putImageData(imageData, 0, row);
}
let dataURL = canvas.toDataURL("image/png");
let img = document.createElement("img");
img.src = dataURL;
let texture2D = new cc.Texture2D();
texture2D.initWithElement(img);
let spriteFrame = new cc.SpriteFrame();
spriteFrame.setTexture(texture2D);
let node = new cc.Node();
let sprite = node.addComponent(cc.Sprite);
sprite.spriteFrame = spriteFrame;
resolve(spriteFrame);
});
}
export function captureAvatar(avatar,frame) {
return new Promise<string>((resolve, reject) => {
let canvas = document.createElement("canvas");
let w = 600;
let h = 600;
canvas.width = w;
canvas.height = h;
let ctx = canvas.getContext("2d");
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(255, 255, 255, 0)";
ctx.fill();
let img = document.createElement("img");
img.src = frame;
let bgImage = document.createElement("img");
bgImage.src = avatar;
bgImage.crossOrigin = "Anonymous";
bgImage.onload = function () {
let circle = {
x: w / 2,
y: h / 2,
r: w / 2,
};
ctx.clearRect(0, 0, w, h);
ctx.save();
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2, false);
ctx.clip();
ctx.drawImage(bgImage, 0, 0, 600, 600);
ctx.drawImage(img, 0, 0, 600, 600);
let base64 = canvas.toDataURL("image/png");
resolve(base64);
};
});
}
export function clearEmpty(obj: any) {
const clearFun = () => {
for (const key in obj) {
if (
["[object Object]"].includes(
Object.prototype.toString.call(obj[key])
) &&
Object.keys(obj[key]).length > 0
) {
clearEmpty(obj[key]);
} else {
if (
["", null, undefined].includes(obj[key]) ||
(["[object Object]"].includes(
Object.prototype.toString.call(obj[key])
) &&
Object.keys(obj[key]).length === 0)
) {
delete obj[key];
}
}
}
return obj;
};
clearFun();
return clearFun();
}
export function isToday(timeStamp){
if(!timeStamp) return false;
return !!(new Date(Number(timeStamp)).toDateString() === new Date().toDateString());
}
export function getCanvas() {
return <any>director.getScene().getChildByName("Canvas");
}
export function decode(input) {
const _utf8_decode = function (utftext) {
let string = "";
let i = 0;
let c = 0;
let c1 = 0;
let c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if ((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
} else {
c1 = utftext.charCodeAt(i + 1);
c2 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return string;
}
let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
let output = "";
let chr1, chr2, chr3;
let enc1, enc2, enc3, enc4;
let i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = _utf8_decode(output);
return output;
}
export function isObj(obj) {
return ["[object Object]"].includes(Object.prototype.toString.call(obj));
}
export function updateProps(targetParams, params) {
if (!targetParams ?? !isObj(targetParams)) targetParams = {};
if (!isObj(params)) return params;
Object.keys(params).forEach((key) => {
if (isObj(params[key])) {
targetParams[key] = targetParams?.[key] ?? {};
updateProps(targetParams[key], params[key]);
} else {
if (targetParams[key] !== params[key]) {
targetParams[key] = params[key];
}
}
});
return targetParams;
}