I've looked extensively for an answer to this problem and what I found was either outdated or didn't work.
I'm trying to create a 320 x 240 pixel canvas and render some lines that appear pixelated (aliased, with clear edges to each pixel). The system I'm running this on reports a window.devicePixelRatio of 1, and I'm using the same values for the element's width/height as CSS's width/height.
Here is a screenshot of what I'm seeing (a Firefox browser on a Windows system that has system resolution set to 1360 x 768 on the left, and the "ideal" image as I would like to see it on the right - its a mock-up done with a paint program):
Here are the three files I'm using:
let canvas = document.querySelector(".playground-canvas");
let ctx = canvas.getContext("2d");
ctx.fillRect(5, 5, 50, 50);
ctx.beginPath();
ctx.moveTo(4.5, 15.5);
ctx.lineTo(15.5, 220.5);
ctx.lineWidth = 0.5;
ctx.strokeStyle = "red";
ctx.stroke();
* {
box-sizing: border-box;
}
body {
background: #333;
padding: 0;
margin: 0;
overflow: hidden;
}
.playground-container {
position: relative;
width: 320px;
height: 240px;
margin: 0 auto;
outline: 1px solid #fff;
transform: scale(2) translateY(30%);
}
.playground-container canvas {
image-rendering: pixelated;
}
<!DOCTYPE html>
<html>
<head>
<title>The Ideal Playground</title>
<link href="playground.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="playground-container">
<canvas class="playground-canvas" width="320" height="240"></canvas>
</div>
<script src="playground.js"></script>
</body>
</html>
I'm guessing I'm trying to ask something of HTML/CSS/JS that it just can't reliably do in today's world of high-DPI displays, etc.
Any help appreciated, thanks.