canvas-confetti icon indicating copy to clipboard operation
canvas-confetti copied to clipboard

set dpr on the canvas, for optimal quality

Open catdad opened this issue 6 years ago • 1 comments

function setupCanvas(canvas) {
  // Get the device pixel ratio, falling back to 1.
  var dpr = window.devicePixelRatio || 1;
  // Get the size of the canvas in CSS pixels.
  var rect = canvas.getBoundingClientRect();
  // Give the canvas pixel dimensions of their CSS
  // size * the device pixel ratio.
  canvas.width = rect.width * dpr;
  canvas.height = rect.height * dpr;
  var ctx = canvas.getContext('2d');
  // Scale all drawing operations by the dpr, so you
  // don't have to worry about the difference.
  ctx.scale(dpr, dpr);
  return ctx;
}

// Now this line will be the same size on the page
// but will look sharper on high-DPI devices!
var ctx = setupCanvas(document.querySelector('.my-canvas'));
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);
ctx.stroke();

https://www.html5rocks.com/en/tutorials/canvas/hidpi/

catdad avatar Feb 22 '19 02:02 catdad

Probem with the solution: breaks all further scaling operations further down on canvas

nelsonvassalo avatar Jul 13 '22 23:07 nelsonvassalo