HTML5画布描边()粗且模糊
我试图允许用户在画布上绘制一个矩形(如选择框)。我得到了一些荒谬的结果,但后来我注意到,即使只是尝试参考此处中的代码,我得到了巨大的模糊线,但不知道为什么。
它托管在 dylanstestserver.com/drawcss。 javascript 是内联的,所以你可以检查一下。我正在使用 jQuery 来简化获取鼠标坐标的过程。
I'm trying to allow the user to draw a rectangle on the canvas (like a selection box). I'm getting some ridiculous results, but then I noticed that even just trying the code from my reference here, I get huge fuzzy lines and don't know why.
it's hosted at dylanstestserver.com/drawcss. the javascript is inline so you can check it out. I am using jQuery to simplify getting the mouse coordinates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果使用css设置canvas的高度和宽度而不是在canvas元素中设置高度和宽度,就会出现模糊的问题。
The blurry problem will happen if you use css to set the canvas height and width instead of setting height and width in the canvas element.
由于某种原因,你的画布被拉伸了。因为您将其 css 属性
width
设置为100%
,所以它会从某种本机大小拉伸它。这是使用 csswidth
属性和标记上的
width
属性之间的区别。您可能想尝试使用一些 JavaScript 来使其填充视口(请参阅 jQuery .width()):For some reason, your canvas is stretched. Because you have its css property
width
set to100%
, it is stretching it from some sort of native size. It's the difference between using the csswidth
property and thewidth
attribute on the<canvas>
tag. You might want to try using a bit of javascript to make it fill the viewport (see jQuery .width()):我的做法是在css中将canvas元素设置为宽度和高度,然后设置canvas.width = canvas.clientWidth和canvas.height = canvas.clientHeight
The way I do it is to set the canvas element to a width and height in the css, and then set the canvas.width = canvas.clientWidth and canvas.height = canvas.clientHeight
您没有以像素为单位指示画布大小,因此它被放大了。这里是300x150。尝试设置宽度、高度
You haven't indicated canvas size in pixels, so it is scaled up. It is 300x150 here. Try setting the width, height
在视网膜显示器上,您还需要缩放(除了接受的答案之外):
On retina displays you also need to scale (in addition to the accepted answer):
这些评论中提到的 css 大小问题是正确的,但另一个可能导致线条模糊的更微妙的事情是忘记在绘制线条之前调用
context.beginPath()
。如果不调用它,您仍然会得到一条线,但它不会被平滑,这使得该线看起来像一系列步骤。The css sizing issue mentioned in these comments is correct, but another more subtle thing that can cause blurred lines is forgetting to call make a call to
context.beginPath()
before drawing a line. Without calling this, you will still get a line, but it won't be smoothed which makes the line looks like a series of steps.我发现我的模糊的原因是内联宽度和 CSS 宽度之间存在细微的差异。
我将内联宽度/高度参数和 css 宽度/高度分配给我的画布,因为我需要保持其物理尺寸静态,同时增加视网膜屏幕的内联尺寸。
如果你有像我这样的情况,请检查你的情况是否相同。
I found the reason mine was blurry was that there was a slight discrepancy between the inline width and the CSS width.
I have both inline width/height parameters AND css width/height assigned to my canvas, because I need to keep its physical dimensions static, while increasing its inline dimensions for retina screens.
Check yours are the same if you have a situation like mine.