【问题标题】:Drawing anti-aliased round-capped line with canvas用画布绘制抗锯齿圆顶线
【发布时间】:2018-04-22 16:19:47
【问题描述】:

我正在尝试为音频播放器创建一个风格化的时间线。我想在末端画一条带有圆帽的粗线。我认为使用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>

我的结果:

与 W3Schools 结果比较:

我从theseposts 了解到矢量抗锯齿是由浏览器决定的。另请注意,我已经尝试过将画布平移半像素以使其进入抗锯齿模式的技巧。如果没有办法让canvas 得到我想要它做的事情,还有其他方法吗?鉴于我只想创建一个相对简单的形状...

【问题讨论】:

  • 您正在使用 css 规则扭曲画布。

标签: javascript canvas html5-canvas antialiasing


【解决方案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>

【讨论】:

  • 谢谢!我确实想知道百分比宽度是否有问题,并将其替换为像素宽度。那么CSS的宽高和canvas的宽高属性有区别吗?为了实现 60% 宽度样式的行为,是否有必要通过带有 resize 事件侦听器的 JavaScript 调整大小?
猜你喜欢
  • 1970-01-01
  • 2013-12-04
  • 2023-03-29
  • 2010-10-03
  • 2015-08-15
  • 2011-08-27
  • 1970-01-01
  • 2010-12-19
  • 2012-12-12
相关资源
最近更新 更多