Reputation: 1410
I had a quick question regarding the ctx function stroke
along with the usage of rect
. In my code, I draw a rect
and fill it with red. I want to also add a green border around the rect
, but when I use stroke
it seems to create a transparent border, rather than a fully solid line. Why does it do this by default?
Img of result:
My code:
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);
}
Upvotes: 0
Views: 554
Reputation: 105015
Canvas draws its lines straddling your pixel coordinate. So a lineWidth=1 vertical line at x=20 will be drawn from 19.5 to 20.5.
To help clarify your rectangle follow these 2 hints:
Assign the rect's x,y,width,height as integers
Set translate(0.50,0.50) before drawing the rect(s) and unset translate(-0.50,-0.50) afterwards
You can read more about the "why?" here:
http://diveintohtml5.info/canvas.html
Note that these hints help with vertical & horizontal lines, but don't help angled lines & curves.
Upvotes: 1