HTML5、canvas 和strokeRect:有些线条太窄太模糊 [英] HTML5, canvas, and strokeRect: some lines too narrow and blurry

查看:39
本文介绍了HTML5、canvas 和strokeRect:有些线条太窄太模糊的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个愚蠢的简单画布用法:

A stupid simple canvas usage:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.strokeStyle = "#CCCC00";
ctx.lineWidth = 3;
ctx.strokeRect(0, 0, width, height);

生成一个矩形,顶部和左侧的线条较窄:

Yields a rectangle with narrower lines along top and left:

为什么会这样?我需要用填充来抵消吗?很烦.

Why does this happen? Do I need to offset with padding? It's annoying.

推荐答案

2 件事.

首先,奇数 lineWidths (1, 3, 5, ...) 永远不会干净地应用在整数像素值上.这是因为 X 和 Y 指的是像素之间的空间而不是它们的中心.因此,从 [1,1][1,10] 的笔画 1 将一半溢出到左侧像素列的像素中,另一半溢出到右侧.如果你改为从 [1.5,1][1.5,10] 绘制那条线,那么它向左填充一半,向右填充一半,填充整个像素列完美.

First, odd lineWidths (1, 3, 5, ...) will never apply cleanly with drawn on integer pixel values. This is because X and Y refer to the space between pixels rather than their centers. So a stroke of 1 that runs from [1,1] to [1,10] spills half into the pixel on the left column of pixels and half into right. If you instead draw that line from [1.5,1] to [1.5,10] then it fills half to the left, and half to the right, filling up the whole pixel column perfectly.

任何奇数宽度都会显示这种行为,但偶数不会,因为它们在每一侧填充了一个完整的像素,看起来很干净.

Any odd number width will show this behavior, but even numbers will not because they fill a full pixel on each side looking clean.

其次,框被画布的顶部遮住了.当您将 3px 笔划居中于 [0,0] 时,它会向上和向左溢出至 [-1.5,-1.5] 的可见范围之外帆布.所以它看起来只有它应该的一半厚.

Second, the box is obscured by the top of the canvas. When you center your 3px stroke on [0,0] it spills as far up and left as [-1.5,-1.5] which is outside of the visible range of the canvas. So it appears half as thick as it should be.

在此处查看差异证明:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// original box, eclipsed by canvas bounds
ctx.strokeStyle = "#CC0000";
ctx.lineWidth = 3;
ctx.strokeRect(0, 0, 20, 20);

// moved from canvas bounds
ctx.strokeStyle = "#CC0000";
ctx.lineWidth = 3;
ctx.strokeRect(25, 25, 20, 20);

// drawn on half pixel coordinated to precent blurry lines with odd integer line widths.
ctx.strokeStyle = "#CC0000";
ctx.lineWidth = 3;
ctx.strokeRect(50.5, 50.5, 20, 20);

body { margin: 10px }

<canvas id="canvas" width="100" height="100"></canvas>

哪个应该呈现这个:

第一个就像你的代码.第二个从左上边缘移开以显示其宽度均匀.第三个展示了如何在没有亚像素模糊的情况下渲染 3 像素的笔划.

The first one is like your code. The second is moved away from the top left edge to show its uniform in width. And the third shows how to render a 3px stroke without subpixel blurring.

这篇关于HTML5、canvas 和strokeRect:有些线条太窄太模糊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆