)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Easy Canvas Resize

  1. const canvas = document.body.appendChild(
  2.   document.createElement('canvas')
  3. );
  4. const c = canvas.getContext('2d');
  5.  
  6. function resize() {
  7.   canvas.width = window.innerWidth;
  8.   canvas.height = window.innerHeight;
  9.   draw();
  10. }
  11.  
  12. function draw() {
  13.   c.clearRect(0, 0, canvas.width, canvas.height);
  14.   c.fillStyle = 'red';
  15.   // 30% width and height
  16.   c.fillRect(30, 30, 
  17.     window.innerWidth * .3, 
  18.     window.innerHeight * .3);
  19. }
  20.  
  21. resize();
  22. window.addEventListener('resize', resize);

Resizing a canvas is unusual, because setting the width/height of a canvas completely erases it.

If your canvas isn’t animating, you can just redraw after resizing. Depending on what you’re drawing, working in percentages instead of pixel values can make things easier.

If you hit the “Try it out…” button, go into fullscreen and resize your browser window you’ll see things in action.

Semi-golfed Calculator

  1. // "Being clever is not clever"
  2. // -- Bjarne Stroustrup
  3. d = document
  4. b = d.body
  5. a = (e = 'div') => b.appendChild(d.createElement(e))
  6. t = a`input`
  7. s = ''
  8. a()
  9. O = v => t.value = v
  10. '0123456789+-*()/C='.split``.map(v => {
  11.   v == '+' && a()
  12.   _ = a`button`
  13.   _.innerHTML = v
  14.   o = { 
  15.     C(){s = O('')},
  16.     ['='](){O(eval(s))}
  17.   }
  18.   _.onclick = () => o[v] ? o[v]() : (s = s + v, O(s))
  19. })
// dom // golfed // javascript // math // tricks

createElement and Object.assign

  1. const el = document.createElement('div');
  2. Object.assign(el.style, {
  3.   position: 'absolute',
  4.   left: '100px',
  5.   top: '100px',
  6.   width: '30px',
  7.   height: '30px',
  8.   background: 'linear-gradient(black, red)',
  9.   transform: 'rotate(15deg)'
  10. });
  11. document.body.appendChild(el);

Fast and easy way to set many styles on a DOM node. Click/tap the “Try it out” button to play around with the code.

// css // dom // tricks
snippet.zone ~ 2021-24 /// {s/z}