Reputation: 148524
I have this simple code of setting rectangle.
I'm stroking its border with a black color.
However , I dont see any black here but gray.
<!doctype html>
<html lang="en">
<canvas id="canvas" width=300 height=300></canvas>
<script>
function draw()
{
ctx.beginPath();
ctx.strokeStyle = "#000000";
ctx.strokeRect(rect.x, rect.y, rect.w, rect.h);
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
var rect = {
x: 10,
y: 10,
w: 40,
h: 100
};
draw();
</script>
</html>
Question :
What am I doing wrong and how can I set the color to be as I define ?
Upvotes: 1
Views: 674
Reputation: 2034
When you create a canvas line, it will make a line passing through the points you declared, and with a width of lineWidth
. If the line is between 2 pixels (for example when you create a line passing through borders, meaning you choose integer values for x and y) it will dissolve the color to balance the 2 pixels your line is crossing, in this case 50% to the pixel on the left, and 50% to the pixel on the right, resulting in a greyish color.
Adding .5
to your x and y makes the line always stay in 1 pixel
<!doctype html>
<html lang="en">
<canvas id="canvas" width=300 height=300></canvas>
<script>
function draw()
{
ctx.beginPath();
ctx.strokeStyle = "#000000";
ctx.strokeRect(rect.x, rect.y, rect.w, rect.h);
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
var rect = {
x: 10.5,
y: 10.5,
w: 40,
h: 100
};
draw();
</script>
</html>
If you run the snippet you'll see that the lines are straight black, and occupying only 1 pixel in width. I just added .5 to your x and y
Upvotes: 2