我有设置矩形的简单代码。
我正在用黑色抚摸它的边框。
但是,我在这里没有看到任何黑色,只有灰色。
<!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>
问题:
我做错了什么以及如何将颜色设置为我定义的颜色?
最佳答案
当您创建 Canvas 线时,它会生成一条线穿过您声明的点,并且线的宽度为lineWidth
。如果该线介于 2 个像素之间(例如,当您创建一条穿过边界的线时,这意味着您为 x 和 y 选择整数值)它将溶解颜色以平衡您的线穿过的 2 个像素,在这种情况下为 50% 到左边的像素,50% 到右边的像素,导致颜色偏灰。
将 .5
添加到您的 x 和 y 使线始终保持在 1 个像素
<!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>
如果您运行该代码段,您会看到线条是直的黑色,并且仅占用 1 个像素的宽度。我刚刚将 .5 添加到你的 x 和 y
关于javascript - 将真彩色设置为 Canvas 边框描边?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25974224/