gpt4 book ai didi

javascript - Canvas 可以在手机上拉伸(stretch),但不能在电脑上拉伸(stretch)

转载 作者:行者123 更新时间:2023-12-03 11:11:53 25 4
gpt4 key购买 nike

我一直在尝试使用 html Canvas ,但由于某种原因,很难让它不拉伸(stretch)东西。我试过只使用 screen.width 和 screen.height,但我通过使用 screen.availWidth 和 screen.availHeight 在 pc 上获得了更好的结果。这是它在我的电脑上的样子(使用 Windows):

enter image description here

这是我手机上的样子(使用 safari):

enter image description here

显然,这两个都不是完美的圆。这是我的js:

const c = document.getElementById("canvas");
const canvas = c.getContext("2d");

function makeCircle()
{
canvas.beginPath();
canvas.arc(200, 400, 50, 0, 2 * Math.PI);
canvas.stroke();
}

function main()
{
c.width = screen.availWidth;
c.height = screen.availHeight;
makeCircle();
}

main();

这是html:
<head>
<title>Canvas</title>
<link rel = "stylesheet" href = "styles.css">
</head>
<body>
<canvas id = "canvas" width="1500" height="952" style="position: fixed; top: 0px; left: 0px; width: 100%; height: 100%; z-index: -1;"></canvas>
<h1 id = "title">Canvas</h1>
<ul id = "navigationBar">
<li><a href = "home.html">Home</a></li>
<li><a href = "lists.html">Lists</a></li>
<li><a href = "canvas.html">Canvas</a></li>
<li><a href = "contacts.html">Contact</a></li>
</ul>
<script src = "canvas.js" charset = "utf-8"></script>
</body>

最佳答案

这里的问题是您已将 Canvas 的显示大小设置为窗口大小的宽度和高度的 100%,这与其固有大小不同,因此 Canvas 试图适应显示的大小,从而扭曲了圆圈。您可以执行以下操作来设置相同的显示尺寸和固有尺寸:

// intrinsic size
c.width = window.innerWidth;
c.height = window.innerHeight;

// and the displayed size is already set to 100% width & height

片段:

const c = document.getElementById("canvas");
const canvas = c.getContext("2d");

window.onresize = function()
{
main();
}

function makeCircle()
{
canvas.beginPath();
canvas.arc(200, 100, 50, 0, 2 * Math.PI);
canvas.stroke();
}

function main()
{
c.width = window.innerWidth;
c.height = window.innerHeight;
makeCircle();
}

main();
<canvas id = "canvas" width="1500" height="952" style="position: fixed; top: 0px; left: 0px; width: 100%; height: 100%; z-index: -1;"></canvas>

关于javascript - Canvas 可以在手机上拉伸(stretch),但不能在电脑上拉伸(stretch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61975588/

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