32

我试图让用户在画布上绘制一个矩形(如选择框)。我得到了一些荒谬的结果,但后来我注意到,即使只是尝试我参考这里的代码,我也会得到巨大的模糊线条,不知道为什么。

它托管在dylanstestserver.com/drawcss 上。javascript是内联的,所以你可以检查出来。我正在使用 jQuery 来简化获取鼠标坐标的过程。

4

7 回答 7

63

如果您使用 css 设置画布高度和宽度,而不是在画布元素中设置高度和宽度,则会出现模糊问题。

<style>
  canvas { height: 800px; width: 1200px; }      WRONG WAY -- BLURRY LINES
</style>

<canvas height="800" width="1200"></canvas>     RIGHT WAY -- SHARP LINES
于 2012-10-12T16:00:09.840 回答
36

由于某种原因,您的画布被拉伸了。因为您将其 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');
    //...
于 2010-10-21T19:44:34.820 回答
12

我这样做的方法是在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");
于 2016-02-18T00:17:03.857 回答
4

You haven't indicated canvas size in pixels, so it is scaled up. It is 300x150 here. Try setting the width, height

于 2010-10-21T19:52:40.343 回答
4

在视网膜显示器上,您还需要缩放(除了接受的答案):

var context = canvas.getContext('2d');
context.scale(2,2);
于 2014-05-20T22:35:15.633 回答
2

这些评论中提到的 css 大小问题是正确的,但另一个可能导致线条模糊的更微妙的事情是context.beginPath()在绘制线条之前忘记调用 make a call to。如果不调用这个,你仍然会得到一条线,但它不会被平滑,这使得线看起来像一系列步骤。

于 2015-01-21T08:49:20.723 回答
0

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.

于 2014-08-30T21:56:58.740 回答