import { createCanvas } from "../../utils";



/**
 * Creates a Canvas element of the given size.
 * 其实就是一个离屏canvas，webgl模式不需要建canvas，因为可以用帧缓存
 */
export default class CanvasRenderTarget {
    /**
     * The Canvas object that belongs to this CanvasRenderTarget.
     */
    canvas: HTMLCanvasElement;
    /**
     * A CanvasRenderingContext2D object representing a two-dimensional rendering context.
     */
    context: CanvasRenderingContext2D;

    /**
     * @param {number} width - the width for the newly created canvas
     * @param {number} height - the height for the newly created canvas
     */
    constructor(width: number, height: number) {

        this.canvas = createCanvas() //document.createElement('canvas');
        // console.log("rd1",this.canvas)
        this.resize(width, height);//要先设置尺寸？
        this.context = this.canvas.getContext('2d');
        // console.log("rd",this.context)
        this.resize(width, height);//为何要多加一次
        this.clear();//淘宝canvas问题，绘制前必须调用过clearRect，否则就有几率绘制不出来
    }

    /**
     * Clears the canvas that was created by the CanvasRenderTarget class.
     *
     * @private
     */
    clear() {
        this.context.setTransform(1, 0, 0, 1, 0, 0);
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }

    /**
     * Resizes the canvas to the specified width and height.
     *
     * @param {number} width - the new width of the canvas
     * @param {number} height - the new height of the canvas
     */
    resize(width: number, height: number): void {
        this.canvas.width = width;
        this.canvas.height = height;
    }

    /**
     * Destroys this canvas.
     *
     */
    destroy() {
        this.context = null;
        this.canvas = null;
    }

    /**
     * The width of the canvas buffer in pixels.
     *
     * @member {number}
     */
    get width(): number {
        return this.canvas.width;
    }

    set width(val: number) {
        this.canvas.width = val;
    }

    /**
     * The height of the canvas buffer in pixels.
     *
     * @member {number}
     */
    get height(): number {
        return this.canvas.height;
    }

    set height(val: number) {
        this.canvas.height = val;
    }
}
