HTML5,canvas和strokeRect:线条更窄? [英] HTML5, canvas, and strokeRect: lines narrower?

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

问题描述

愚蠢的简单画布用法:

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.

推荐答案

两件事。

第一,奇数线宽(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.

在此处查看差异证明:
http://jsfiddle.net/F4cqk/2/

See the proof of difference here: http://jsfiddle.net/F4cqk/2/

第一个一个就像你的代码。第二个从左上边缘移开以显示其宽度均匀。第三个显示了如何在不引起子像素模糊的情况下渲染3px笔触。

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天全站免登陆