JSFiddle - React, Tailwind, and code Playground

by Arjan Haverkamp

HTML

<h1>Fiddle for SnapDom <tt>dpr</tt> issues</h1>
<p>Run this fiddle on a screen that has a devicePixelRatio of &gt; 1, open your console!</p>
<ul>
  <li>The `dpr` option does have effect in `toPng`, while it has no effect in `toImg`</li>
  <li>The `dpr` option has no effect in `toCanvas`</li>
  <li>The `dpr` option has no effect in `download`</li>
  <li>Img export vs Canvas export yield different dimensions</li>
</ul>


<canvas id="canvas"></canvas>
<hr>
<button id="imgBtn">Image</button>
<button id="canvasBtn">Canvas</button>
<button id="downloadBtn">Download</button>

CSS

body {
  font-family: Sans-serif;
}
canvas {
  max-width: 100%;
  height: auto;
  display: block;
  outline: 1px dotted #000;
}

JavaScript

const canvasWidth = 800, canvasHeight = 300;
const canvasEl = document.querySelector('#canvas');
canvasEl.width = canvasWidth;
canvasEl.height = canvasHeight;

const ctx = canvasEl.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, canvasWidth, canvasHeight);

document.querySelector('#imgBtn').onclick = async () => {
  const result = await snapdom(canvasEl);
  const image1 = await result.toPng({width:canvasWidth, height:canvasHeight, dpr:1}); 
  console.log('image1 dims', `${image1.naturalWidth}x${image1.naturalHeight}`); // 800x300 (correct)
  
  const image2 = await snapdom.toPng(canvasEl, { width:canvasWidth, height:canvasHeight, dpr:1 /* does have effect */ });
  console.log('image2 dims', `${image2.naturalWidth}x${image2.naturalHeight}`); // 800x300 (correct)

  const image3 = await snapdom.toImg(canvasEl, { width:canvasWidth, height:canvasHeight, dpr:2 /* no effect */, type:'png' });
  // Oopsie: the 'dpr' option does not have any effect here
  console.log('image3 dims', `${image3.naturalWidth}x${image3.naturalHeight}`); // 800x300 (incorrect, should be 1600x600 because of dpr:2)
}

document.querySelector('#canvasBtn').onclick = async () => {
  const result = await snapdom(canvasEl);
  const canvas1 = await result.toCanvas({width:canvasWidth, height:canvasHeight, dpr:1});
  console.log('canvas1 dims', `${canvas1.width}x${canvas1.height}`); // 1460x549 (incorrect, should be 800x300)

  const canvas2 = await snapdom.toCanvas(canvasEl, { width:canvasWidth, height:canvasHeight, dpr:1 /* no effect */});
  console.log('canvas2 dims', `${canvas2.width}x${canvas2.height}`); // 1778x667 (incorrect, should be 800x300)

  const canvas3 = await snapdom.toCanvas(canvasEl, { width:canvasWidth, height:canvasHeight, dpr:2 /* no effect */});
  console.log('canvas3 dims', `${canvas3.width}x${canvas3.height}`); // 1778x667 (incorrect, should be 1600x600 because of dpr:2)
}

document.querySelector('#downloadBtn').onclick = async ()...