Canvas stretches out on phones but not on computer

Viewed 38

I've been trying to use the html canvas but for some reason it's super difficult to get it to not stretch stuff out. I've tried using just screen.width and screen.height but I get a better result on pc by using screen.availWidth and screen.availHeight. Here's what it looks like on my pc (using windows):

enter image description here

And here's what it looks like on my phone (using safari):

enter image description here

Obviously, neither of these are perfect circles. Here's my 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();

And here's the 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>
1 Answers

The problem here is that you have set the displayed size of the canvas as 100% of width and height of the window size which is not same as it's intrinsic size and thus the canvas tries to fit in the displayed size, distorting the shape of the circle. You can do something like this to set the same displayed and intrinsic sizes:

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

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

Snippet:

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>

Related