【发布时间】: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