简体   繁体   English

HTML5画布线宽小于1像素

[英]HTML5 canvas line width less that 1 pixel

Is there any way to draw a rectangle whose composing lines have width thinner than 1 pixel? 有没有办法绘制一个矩形,其构图线的宽度比1像素宽?

This code works perfectly, as expected: 正如预期的那样,此代码完美地运行

// context is a HTML5 canvas 2D context
context.lineWidth = 1;
context.strokeStyle = "black";
context.rect(0, 0, 20, 20);
context.stroke();

It draws a nice rectangle. 它绘制了一个漂亮的矩形。

But, if I try to draw a rectangle with thinner lines: 但是,如果我尝试绘制一条更细的线条:

// See line width
context.lineWidth = 0.5;
context.strokeStyle = "black";
context.rect(0, 0, 20, 20);
context.stroke();

It still draws a rectangle whose borders have 1 pixel width. 它仍然绘制一个边框宽度为1像素的矩形。

I'm dealing with the canvas object here, and not CSS, where you have ways to "simulate" this. 我在这里处理canvas对象,而不是CSS,你有办法“模拟”这个。

Although it doesn't make much sense, you can acheive that with using a regular 1-pixel line with a 50% scaled canvas (but again it's a 1-pixel rendition, read below). 虽然它没有多大意义,但你可以通过使用带有50%缩放画布的常规1像素线来实现这一点(但同样是1像素再现,请阅读下文)。 See this snippet: 看到这个片段:

 var canvas = document.querySelector('canvas'); var context = canvas.getContext('2d'); function scale() { context.scale(0.5, 0.5); draw(); } function draw() { context.beginPath(); context.moveTo(100, 150); context.lineTo(450, 50); context.stroke(); } draw() 
 <canvas width="400" height="150"></canvas> <button onclick="scale()">Scale down</button> 


But again, I wonder how you expect the half-pixel line to look on your screen, antialiasing? 但同样,我想知道您希望半像素线在屏幕上看起来如何抗锯齿?

Right :) I suppose I was thinking on some way of drawing thinner lines, like, for example, when you use CSS styles. 正确:)我想我正在考虑绘制更细线的某种方式,例如,当您使用CSS样式时。 I've looked around and I don't think I can use alternate units. 我环顾四周,我认为我不能使用替代单位。

There's no way to make something that's smaller than the smallest component unit, in our case a pixel. 没有办法制作比最小元件单元小的东西,在我们的例子中是一个像素。 You can mimic the thinner look by transparency, or opacity, or even some sort of antialiasing (which again relies on transparency or the colouring of the neighbouring pixels), but not by trying to go below one pixel. 您可以通过透明度,不透明度,甚至某种抗锯齿(再次依赖于透明度或相邻像素的着色)来模仿较薄的外观,但不能通过尝试低于一个像素。

I agree, there is a sub-pixel rendering mode in browsers, for example, when you work with percentages, but in the end, the browser just renders full pixels with some of the modification I've described above. 我同意,在浏览器中有一个子像素渲染模式,例如,当您使用百分比时,但最后,浏览器只使用我上面描述的一些修改来渲染完整像素。


And you know if you could render unit smaller than pixels, you'd technically have infinite resolutions on displays. 而且你知道如果渲染单位小于像素,你在技术上会在显示器上有无限的分辨率。 I wish it was possible. 我希望有可能。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM