使用画布

时间:2018-04-22 16:19:48

标签: javascript canvas html5-canvas antialiasing

我正在尝试为音频播放器创建一个风格化的时间轴。我想在末端绘制一条带圆帽的粗线。我认为用canvas做这件事会相对微不足道。但是,我发现至少在Mac OS上的Chrome中,线条没有消除锯齿;并且(可能因此)线帽是细长的,而不是完美的半圆。

让我感到困惑的是,当我查看W3 Schools example消除锯齿时,带有预期上限。这让我想知道我的代码中是否有东西在浏览器中触发了非抗锯齿模式......

这是我的完整代码:

<html>
<head>
    <style>

        body {
            background-color: #212b69;
        }

        .centering {
            height: 100%;
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        #timeline {
            width: 60%;
            height: 50px;
        }

    </style>
</head>
<body>
    <div class="centering">
        <canvas id="timeline" />
    </div>
    <script type="text/javascript">

        var timeline = document.getElementById('timeline');
        var ctx = timeline.getContext('2d');
        var centrline = timeline.height/2;

        // ctx.translate(0.5, 0.5); // I have tried the half-pixel trick

        // line settings
        ctx.lineCap = "round";
        ctx.lineWidth = 30;
        ctx.strokeStyle = "white";

        // draw test stroke
        ctx.beginPath();
        ctx.moveTo(20, centrline);
        ctx.lineTo(60, centrline+10); // offset to show aliasing of edges
        ctx.stroke();

    </script>
</body>
</html>

我的结果:

aliased line screenshot

与W3Schools结果相比:

anti-aliased line from W3Schools

我从these posts了解到,矢量消除锯齿是由浏览器决定的。另请注意,我尝试了将画布转换为半像素以使其进入抗锯齿模式的技巧。如果没有办法让canvas得到我想要的东西,还有其他方法吗?鉴于我只想创建一个相对简单的形状......

1 个答案:

答案 0 :(得分:1)

只需删除以下css规则,形状就会停止倾斜。

#timeline {
            width: 60%;
            height: 50px;
        }

这是一个没有偏斜的工作示例:enter link description here

var timeline = document.getElementById('timeline');
        var ctx = timeline.getContext('2d');
        var centrline = timeline.height/2;

        // ctx.translate(0.5, 0.5); // I have tried the half-pixel trick

        // line settings
        ctx.lineCap = "round";
        ctx.lineWidth = 30;
        ctx.strokeStyle = "white";

        // draw test stroke
        ctx.beginPath();
        ctx.moveTo(20, centrline);
        ctx.lineTo(60, centrline+10); // offset to show aliasing of edges
        ctx.stroke();
body {
  background-color: #212b69;
}

.centering {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="centering">
        <canvas id="timeline" />
    </div>

相关问题