Canvas blurry vs sharp using window.devicePixelRatio
From MDN
by keithphw
HTML
<canvas id="canvas"></canvas>
<canvas id="canvas2"></canvas>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
JavaScript
// from
// https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
{let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
// Set display size (css pixels).
let size = 200;
canvas.style.width = size + "px";
canvas.style.height = size + "px";
// Set actual size in memory (scaled to account for extra pixel density).
let scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas.
canvas.width = size * scale;
canvas.height = size * scale;
// Normalize coordinate system to use css pixels.
ctx.scale(scale, scale);
ctx.fillStyle = "#bada55";
ctx.fillRect(10, 10, 300, 300);
ctx.fillStyle = "#ffffff";
ctx.font = '18px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
let x = size / 2;
let y = size / 2;
let textString = "ratio:"+scale;
ctx.fillText(textString, x, y);
zoom = parseInt(document.defaultView.getComputedStyle(document.documentElement, null).width,10)/document.documentElement.clientWidth;
ctx.fillText("userzoom:"+zoom, x, y+20)
}
{let canvas = document.getElementById('canvas2');
let ctx = canvas.getContext('2d');
// Set display size (css pixels).
let size = 200;
canvas.style.width = size + "px";
canvas.style.height = size + "px";
// Set actual size in memory (scaled to account for extra pixel density).
let scale = 1;//window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas.
canvas.width = size * scale;
canvas.height = size * scale;
// Normalize coordinate system to use css pixels.
ctx.scale(scale, scale);
ctx.fillStyle = "#bada55";
ctx.fillRect(10, 10, 300, 300);
ctx.fillStyle = "#ffffff";
ctx.font = '18px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
let x = size / 2;
let y = size / 2;
let textString = "ratio:"+scale;
ctx.fillText(textString, x, y);
}