【问题标题】:Canvas stretches out on phones but not on computer画布可以在手机上伸展,但不能在电脑上伸展
【发布时间】:2020-05-28 15:56:56
【问题描述】:

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

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

显然,这些都不是完美的圆。这是我的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>

【问题讨论】:

  • &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;

标签: javascript html windows canvas html5-canvas


【解决方案1】:

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

// 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();
&lt;canvas id = "canvas" width="1500" height="952" style="position: fixed; top: 0px; left: 0px; width: 100%; height: 100%; z-index: -1;"&gt;&lt;/canvas&gt;

【讨论】:

  • 我刚刚发现这个解决方案的一个问题是,当我在计算机上打开检查器时,由于某种原因它会扭曲画布
  • 它会因为同样的原因而扭曲,因为现在显示尺寸发生了变化,内在尺寸是相同的。您可以添加一个侦听器以调整窗口大小并更新画布的大小并再次绘制弧线。我已经编辑了答案。
猜你喜欢
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 2011-07-02
  • 2021-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多