画布上下文的stroke()会产生透明边框,而不是完全不透明?

时间:2014-12-29 19:47:00

标签: html5-canvas

我有一个关于ctx函数stroke的快速问题以及rect的用法。在我的代码中,我绘制了一个rect并用红色填充它。我还希望在rect周围添加绿色边框,但是当我使用stroke时,它似乎创建了一个透明边框,而不是一个完全实线。为什么默认情况下会这样做?

结果:

enter image description here

我的代码:

        var ctx = Canvas.ctx;

        ctx.beginPath();
        ctx.rect(this.x, this.y, this.width, this.height);

        /*
         *  CONTAINER
         */
        ctx.fillStyle = this.primaryColor;
        ctx.fill();

        /*
         *  CONTAINER BAR
         */
        if(this.borderColor){
            ctx.strokeStyle = this.borderColor;
            ctx.stroke();
        }

        /*
         *  INNER BAR
         */
        var per = this.percent;

        if(per > 0){
            //the width of the actual loading bar that appears
            //inside the entire box
            var innerWidth = Math.floor(this.width*(per/100));

            ctx.fillStyle = this.secondaryColor;
            ctx.fillRect(this.x+1, this.y+1, innerWidth-2, this.height-2);
        }

        /*
         *  TEXT
         */
        if(this.text){
            ctx.textAlign = this.textAlign;
            ctx.font = this.font;
            ctx.fillStyle = this.textColor;
            ctx.fillText(this.text, this.textX, this.textY);
        }

1 个答案:

答案 0 :(得分:1)

Canvas绘制其跨越像素坐标的线条。因此,x = 20处的lineWidth = 1垂直线将从19.5到20.5绘制。

为了帮助澄清您的矩形,请遵循以下两个提示:

  • 将rect的x,y,width,height分配为整数

  • 在绘制矩形之前设置平移(0.50,0.50)并在之后取消设置平移(-0.50,-0.50)

您可以详细了解“为什么?”这里:

http://diveintohtml5.info/canvas.html

请注意,这些提示有助于垂直和&水平线,但不帮角度线和&曲线。

相关问题