javascript HTML5 画布抗锯齿?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6032263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:12:55  来源:igfitidea点击:

HTML5 canvas anti-alias?

javascripthtml5-canvas

提问by wong2

I'm trying to draw a quadratic curve with canvas. Here is the code:
HTML:

我正在尝试用画布绘制二次曲线。这是代码:
HTML:

<canvas id="mycanvas"> 
    Your browser is not supported.
</canvas> 

JavaScript:

JavaScript:

var canvas = document.getElementById("mycanvas");
canvas.style.width = "1000px";
canvas.style.height = "1000px";
if (canvas.getContext) {
    var ctx = canvas.getContext("2d");
    var x = 0,
        y = 0;
    setInterval(function() {
        ctx.lineTo(x, y);
        ctx.stroke();
        x += 1;
        y = 0.01 * x * x;
    }, 100);
}

But the result is really ugly, first, the lines are too thick, second, the alias is so obvious.... how could I improve it?
You can see the effect here: http://jsfiddle.net/7wNmx/1/

但是结果真的很难看,一是线条太粗,二是别名太明显了....怎么改进呢?
你可以在这里看到效果:http: //jsfiddle.net/7wNmx/1/

采纳答案by Brian Campbell

What you're doing is creating a canvas which is the default size, 300 by 150, and then scaling it up using CSS to 1000px by 1000px. But scaling it up like that just magnifies the size of the pixels, it doesn't increase the resolution of the canvas itself. What you need to do is set the actual dimensions of the canvas itself using the widthand heightattributes:

您正在做的是创建一个默认大小为 300 x 150 的画布,然后使用 CSS 将其放大到 1000 像素 x 1000 像素。但是像这样放大只会放大像素的大小,并不会增加画布本身的分辨率。您需要做的是使用widthheight属性设置画布本身的实际尺寸:

<canvas width="1000" height="1000" id="mycanvas"> 
    Your browser is not supported.
</canvas>

Then you don't need to scale it up by setting canvas.style.widthand heightany more.

然后你不需要通过设置canvas.style.width等来扩大它height

回答by pimvdb

Another thing is that you're stroking eachtime. So the first line is drawn most, whilst the second is drawn one less time, etc.

另一件事是你每次都在抚摸。所以第一条线被绘制得最多,而第二条线被绘制的时间更少,依此类推。

This also causes it to become ugly. You'd need to begin a new path and only stroke that one:

这也导致它变得丑陋。您需要开始一条新路径,并且只抚摸那条路径:

var canvas = document.getElementById("mycanvas");
canvas.style.width = "1000px";
canvas.style.height = "1000px";
if (canvas.getContext) {
    var ctx = canvas.getContext("2d");
    var x = 0,
        y = 0;
    setInterval(function() {
        ctx.beginPath();
        ctx.moveTo(x,y)
        x += 1;
        y = 0.01 * x * x;
        ctx.lineTo(x, y);
        ctx.stroke();
    }, 100);
}

Compare:

比较:

http://i.stack.imgur.com/40M20.png

http://i.stack.imgur.com/40M20.png

It's also faster since less drawing is done.

由于完成的绘图较少,因此速度也更快。