我试图让用户在画布上绘制一个矩形(如选择框)。我得到了一些荒谬的结果,但后来我注意到,即使只是尝试我参考这里的代码,我也会得到巨大的模糊线条,不知道为什么。
它托管在dylanstestserver.com/drawcss 上。javascript是内联的,所以你可以检查出来。我正在使用 jQuery 来简化获取鼠标坐标的过程。
我试图让用户在画布上绘制一个矩形(如选择框)。我得到了一些荒谬的结果,但后来我注意到,即使只是尝试我参考这里的代码,我也会得到巨大的模糊线条,不知道为什么。
它托管在dylanstestserver.com/drawcss 上。javascript是内联的,所以你可以检查出来。我正在使用 jQuery 来简化获取鼠标坐标的过程。
如果您使用 css 设置画布高度和宽度,而不是在画布元素中设置高度和宽度,则会出现模糊问题。
<style>
canvas { height: 800px; width: 1200px; } WRONG WAY -- BLURRY LINES
</style>
<canvas height="800" width="1200"></canvas> RIGHT WAY -- SHARP LINES
由于某种原因,您的画布被拉伸了。因为您将其 css 属性width
设置为100%
,所以它正在从某种本机大小拉伸它。width
这是使用 css属性和标签width
上的属性之间的区别。<canvas>
您可能想尝试使用一些 javascript 来填充视口(请参阅 jQuery .width()):
jQuery(document).ready(function(){
var canvas = document.getElementById('drawing');
canvas.width(($(window).width()).height($(window).height());
var context = canvas.getContext('2d');
//...
我这样做的方法是在css中将canvas元素设置为一个宽度和高度,然后设置canvas.width = canvas.clientWidth和canvas.height = canvas.clientHeight
var canvas = document.getElementById("myCanvas");
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
var context = canvas.getContext("2d");
You haven't indicated canvas size in pixels, so it is scaled up. It is 300x150 here. Try setting the width, height
在视网膜显示器上,您还需要缩放(除了接受的答案):
var context = canvas.getContext('2d');
context.scale(2,2);
这些评论中提到的 css 大小问题是正确的,但另一个可能导致线条模糊的更微妙的事情是context.beginPath()
在绘制线条之前忘记调用 make a call to。如果不调用这个,你仍然会得到一条线,但它不会被平滑,这使得线看起来像一系列步骤。
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.