

let env: "tb" | "web" = "web";
//如果是浏览器环境，声明个my为null，为了无声明不报错
if (window) window["my"] = null;//在用webview的小程序环境内，只要在小程序的sdk前加js就无所谓，
export function getEnv(): "tb" | "web" {
    return env
}
/**
 * 创建一个离屏的canvas
 */
export function createCanvas(): HTMLCanvasElement {
    //@ts-ignore
    return document && document.createElement("canvas") || my._createOffscreenCanvas();
}

let contentByCanvas: {
    createImage: () => HTMLImageElement,
    requestAnimationFrame: (fun: Function) => number,
    cancelAnimationFrame: (id) => void,
};
/**
 * 淘宝小程序项目，拿到canvas先执行这个,,,TODO为啥不直接记录canvas.也许有问题,暂时不改
 * @param canvas 
 */
export function initedByCanvas(canvas) {
    contentByCanvas = {
        createImage: canvas.createImage.bind(canvas),
        //必须加bind，函数内存在this指向
        requestAnimationFrame: canvas.requestAnimationFrame.bind(canvas),
        cancelAnimationFrame: canvas.cancelAnimationFrame.bind(canvas),
    }
    env = "tb";
}
export function destroyCanvasContent() {
    if (contentByCanvas) {
        contentByCanvas.createImage = null;
        contentByCanvas.requestAnimationFrame = null;
        contentByCanvas.cancelAnimationFrame = null;
        contentByCanvas = null
    }
}

export function createImage() {
    return contentByCanvas && contentByCanvas.createImage() || new Image();
}
//下面两个尽量自己外层写循环，不用这里的，因为淘宝小程序不同page用了canvas，最好都用各自的requestAnimationFrame，不相互覆盖
export function getRequestAnimationFrame() {
    return contentByCanvas && contentByCanvas.requestAnimationFrame || window.requestAnimationFrame.bind(window)
}
export function getCancelAnimationFrame() {
    return contentByCanvas && contentByCanvas.cancelAnimationFrame || window.cancelAnimationFrame.bind(window)
}

//TODO上面所有的以后考虑这么些写,待测试
// let env: "tb" | "web" = "web";
// //如果是浏览器环境，声明个my为null，为了无声明不报错
// if (window) window["my"] = null;//在用webview的小程序环境内，只要在小程序的sdk前加js就无所谓，
// export function getEnv(): "tb" | "web" {
//     return env
// }
// /**
//  * 创建一个离屏的canvas
//  */
// export function createCanvas(): HTMLCanvasElement {
//     //@ts-ignore
//     return getEnv() == "web" && document.createElement("canvas") || my._createOffscreenCanvas();
// }
// /**
//  * 临时记录的淘宝小程序的主canvas
//  */
// let tbCanvas;
// /**
//  * 淘宝小程序项目，拿到canvas先执行这个,修改当前环境
//  * @param canvas 
//  */
// export function initedByCanvas(canvas) {
//     tbCanvas = canvas;
//     env = "tb";
// }
// export function destroyCanvasContent() {
//     tbCanvas = null;
// }
// export function createImage(): HTMLImageElement {
//     return tbCanvas && tbCanvas.createImage() || new Image();
// }
// export function requestAnimationFrame(callback) {
//     return tbCanvas && tbCanvas.requestAnimationFrame(callback) || window.requestAnimationFrame(callback)
// }
// export function cancelAnimationFrame(id: number) {
//     return tbCanvas && tbCanvas.cancelAnimationFrame(id) || window.cancelAnimationFrame(id)
// }
