Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
Getting crisp pixel-perfect lines using HTML canvas

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): enter image description here

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.

about 4 years ago · Santiago Gelvez
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda