gpt4 book ai didi

javascript - 用 Canvas 绘制抗锯齿圆顶线

转载 作者:行者123 更新时间:2023-11-30 20:34:38 25 4
gpt4 key购买 nike

我正在尝试为音频播放器创建风格化的时间轴。我想画一条漂亮的粗线,两端有圆帽。我认为用 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 平移半个像素以将其踢入抗锯齿模式的技巧。如果没有办法让 canvas 得到我想要它做的事情,还有其他方法吗?鉴于我只想创建一个相对简单的形状...

最佳答案

只需删除以下 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>

关于javascript - 用 Canvas 绘制抗锯齿圆顶线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49968131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com