javascript - HTML Canvas : rectangle stroke appears transparent

标签 javascript html canvas html5-canvas

老实说,我不知道这是我的眼睛在与我 SCSS 还是 Canvas 实际上变得透明了。然而,这个问题对我来说似乎是非常清楚的:当我使用 StrokeRect (描边矩形)时,无论我做什么,描边看起来都是透明的。

查看笔画截图:http://prntscr.com/ijeiu9

查看正常填充的屏幕截图:http://prntscr.com/ijeiz7

我的代码很简单:

context.strokeStyle = "#F5F5F5";
context.strokeRect(128, 488, 400, 26);

这甚至可能是我所知道的默认行为,我该如何“修复”这个问题?

最佳答案

MDN documentation对此情况描述如下:

Obtaining crisp lines requires understanding how paths are stroked. In the images below, the grid represents the canvas coordinate grid. The squares between gridlines are actual on-screen pixels. In the first grid image below, a rectangle from (2,1) to (5,5) is filled. The entire area between them (light red) falls on pixel boundaries, so the resulting filled rectangle will have crisp edges.

If you consider a path from (3,1) to (3,5) with a line thickness of 1.0, you end up with the situation in the second image. The actual area to be filled (dark blue) only extends halfway into the pixels on either side of the path. An approximation of this has to be rendered, which means that those pixels being only partially shaded, and results in the entire area (the light blue and dark blue) being filled in with a color only half as dark as the actual stroke color.

这意味着要获得宽度 1 的清晰线条,您应该从半个像素开始绘制矩形:

let a = document.getElementById("a");
let ac = a.getContext("2d");

ac.strokeStyle = "#F5F5F5";
ac.lineWidth = 1;
ac.strokeRect(20, 20, 150, 100);

let b = document.getElementById("b");
let bc = b.getContext("2d");

bc.strokeStyle = "#F5F5F5";
bc.lineWidth = 1;
bc.strokeRect(20.5, 20.5, 150, 100);
canvas {width: 300px; height: 150px; background-color:black}
<canvas id="a"></canvas>
<canvas id="b"></canvas>

关于javascript - HTML Canvas : rectangle stroke appears transparent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48970578/

相关文章:

注入(inject)函数中的 Javascript 作用域

javascript - 选择选项使用 JQUERY 通过文本获取值

html - 选项卡菜单重叠

javascript - 在 Canvas 上围绕图像的非透明部分绘制边框

android - 创建自定义表单 java android

android - 使用 Canvas 绘制时分别更改文本高度和宽度

JavaScript Promises - 在继续之前等待解决

javascript - 当跨度不包含内容时隐藏父级

css - 在 div 中居中响应图像

php - jQuery 只在用户第一次进入网站时起作用