Skip to content

Instantly share code, notes, and snippets.

@JobLeonard
Created December 1, 2023 16:06
Show Gist options
  • Save JobLeonard/11ede43bcd0b92d7e12704d057d34d1e to your computer and use it in GitHub Desktop.
Save JobLeonard/11ede43bcd0b92d7e12704d057d34d1e to your computer and use it in GitHub Desktop.
Canvas stroke weirdness
canvas {
width: 400px;
height: 400px;
/* Legal fallback */
image-rendering: optimizeSpeed;
/* Firefox */
image-rendering: -moz-crisp-edges;
/* Opera */
image-rendering: -o-crisp-edges;
/* Safari */
image-rendering: -webkit-optimize-contrast;
/* CSS3 Proposed */
image-rendering: optimize-contrast;
/* CSS4 Proposed */
image-rendering: crisp-edges;
/* CSS4 Proposed */
image-rendering: pixelated;
/* IE8+ */
-ms-interpolation-mode: nearest-neighbor;
}
<div><canvas width="400" height="400" id="c"></canvas></div>
<pre>{alpha: false}</pre>
<hr>
<div><canvas width="400" height="400" id="c2"></canvas></div>
<pre>{alpha: true}</pre>
const draw = (id, alpha) => {
const canvas = c = document.createElement("canvas");
canvas.width = canvas.height = 50;
const ctx = canvas.getContext("2d", {alpha});
ctx.fillStyle = "#FFF";
ctx.fillRect(0, 0, 50, 50);
ctx.lineWidth = 1;
ctx.strokeStyle = "#000";
// nope, half a pixel off
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(20, 10);
ctx.lineTo(20, 20);
ctx.lineTo(10, 20);
ctx.lineTo(10, 10);
ctx.closePath();
ctx.stroke();
// still nope, endpoints/corners are partially transparent
ctx.beginPath();
ctx.moveTo(30.5, 10.5);
ctx.lineTo(40.5, 10.5);
ctx.lineTo(40.5, 20.5);
ctx.lineTo(30.5, 20.5);
ctx.lineTo(30.5, 10.5);
ctx.stroke();
// nope, works on Chrome (Linux) but on Firefox (Linux)
// it still has partially transparent endpoints/corners
ctx.save();
ctx.translate(0.5, 0.5);
ctx.beginPath();
ctx.moveTo(10, 30);
ctx.lineTo(20, 30);
ctx.lineTo(20, 40);
ctx.lineTo(10, 40);
ctx.closePath();
ctx.stroke();
ctx.restore();
// seriously, what the heck?!
ctx.beginPath();
ctx.moveTo(30, 30.5);
ctx.lineTo(40.5, 30.5);
ctx.moveTo(40.5, 30);
ctx.lineTo(40.5, 40.5);
ctx.moveTo(41, 40.5);
ctx.lineTo(30, 40.5);
ctx.moveTo(30.5, 40.5);
ctx.lineTo(30.5, 30.5);
ctx.closePath();
ctx.stroke();
ctx.restore();
const ctxZoom = document.getElementById(id).getContext("2d", { alpha: false });
ctxZoom.fillStyle = "#FFF";
ctxZoom.fillRect(0, 0, 400, 400);
ctxZoom.imageSmoothingEnabled = false;
ctxZoom.drawImage(canvas, 0, 0, 400, 400);
ctxZoom.fillStyle = "#000";
ctxZoom.font = "10px sans-serif";
ctxZoom.fillText(navigator.userAgent, 10, 20);
};
draw("c", false);
draw("c2", true);
{"name":"Canvas stroke weirdness","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment