0

Why does setting the canvas size with attributes in JS work correctly:

canvas = document.getElementById('canvas');
canvas.width = 200;
canvas.height = 200;
const ctx = canvas.getContext('2d');
const arr = new Uint8ClampedArray(40000);
for (let i = 0; i < arr.length; i += 4) { arr[i + 0] = 0; arr[i + 1] = 190; arr[i + 2] = 0; arr[i + 3] = 255; }
let imageData = new ImageData(arr, 100, 100);
ctx.putImageData(imageData, 0, 0, 0, 0, 100, 100);
#canvas { border: 1px solid black; }
<canvas id="canvas"></canvas>

whereas setting it directly with CSS totally fails with wrong aspect ratio? (it gives a rectangle instead of a square!)

canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const arr = new Uint8ClampedArray(40000);
for (let i = 0; i < arr.length; i += 4) { arr[i + 0] = 0; arr[i + 1] = 190; arr[i + 2] = 0; arr[i + 3] = 255; }
let imageData = new ImageData(arr, 100, 100);
ctx.putImageData(imageData, 0, 0, 0, 0, 100, 100);
#canvas { border: 1px solid black; height: 200px; width: 200px; }
<canvas id="canvas"></canvas>
Basj
  • 41,386
  • 99
  • 383
  • 673
  • 1
    The CSS height/width are different from that of the canvas's height/width, that is why. Canvas height/width is your drawing zones, CSS scales this so Canvas can be 800x600 logically and the CSS can squish it to 200x300 if you wanted all while maintaining a smaller 800x600 logical. – BGPHiJACK Jun 23 '22 at 09:25
  • @BGPHiJACK I think you can post this as the answer! – Basj Jun 23 '22 at 09:32

0 Answers0