class Graphics {
    constructor(ctx){
        this.ctx = ctx;
        this.ctx.translate(0.5, 0.5);
    }

    setColor(color){
        this.ctx.fillStyle = color;
        this.ctx.strokeStyle = color;
    }

    setFont(font){
        this.ctx.font = font;
    }

    textAlign(align){
        this.ctx.textAlign = align; 
    }

    stringWidth(txt){
        return this.ctx.measureText(txt).width;
    }

    strokeRect(x, y, width, height){
        this.ctx.strokeRect(x, y, width, height);
    }

    translate(x, y){
        this.ctx.translate(x, y)
    }

    fillText(text, x, y){
        this.ctx.fillText(text, x, y);
    }

    fillRect(x, y, width, height){
        this.ctx.fillRect(x, y, width, height);
    }

    fillPolygon(polygon){
        this.ctx.beginPath();
        for(let i = 0; i < polygon.points.length; i++){
            if(i == 0){
                this.ctx.moveTo(polygon.points[i].x,polygon.points[i].y);
            }else{
                this.ctx.lineTo(polygon.points[i].x,polygon.points[i].y);
            }
        }
        this.ctx.fill();
    }

    drawLine (x1, y1, x2, y2){     
        this.ctx.beginPath();
        this.ctx.moveTo(x1, y1);
        this.ctx.lineTo(x2, y2);
        this.ctx.closePath();
        this.ctx.stroke();
    }

    drawImage(image, x, y, width, height){
        this.ctx.drawImage(image, x, y, width, height);
    }

    drawRect(x, y, width, height){
        this.ctx.strokeRect(x, y, width, height);
    }

    drawString(text, x, y){

        this.ctx.strokeText(text, x, y);
    }
    drawArc(x,y,r,staAngle,endAngle,antiClockWise){
        this.ctx.arc(x,y,r,staAngle,endAngle,antiClockWise);
        this.ctx.stroke();
    }
    // yx 计算长度再显示文字[超出第一行显示省略号]
    /**
     * 
     * @param {文字} t 
     * @param {横坐标} x 
     * @param {文字高度} y 
     * @param {显示的文字宽度} w 
     */
    drawText(t,x,y,w=110){
        let chr = t.split("");
        let temp = "";				
        let row = [];
        for(let a = 0; a < chr.length; a++){
            if(this.ctx.measureText(temp).width < w ){
                ;
            }
            else{
                row.push(temp);
                temp = "";
            }
            temp += chr[a];
        }
        
        row.push(temp);
        if(this.ctx.measureText(t).width >w){
            this.ctx.fillText(row[0] + '...',x - 10, y);
        }else
            this.ctx.fillText(row[0],x - 10, y); // 16： 字体大小
    }
}

export default Graphics;