简体   繁体   中英

How to resize HTML canvas in grid layout?

I understand that (and why) resizing an HTML canvas object exactly such that the contents do not scale is tricky. See eg

Now, all the solutions I have seen (using either a simple event handler or a ResizeOberserver ) do not seem to work if the size of the canvas in the browser is determined by a display:grid layout. In that case, the canvas grows in an endless loop.

How can one do this correctly?

If I understood it right the following code should be able to resize the canvas element after a resize event was triggered

window.addEventListener('DOMContentLoaded', () => {
  const canvas = document.getElementsByTagName('canvas')[0]
  window.addEventListener('resize', () => {
    canvas.style.width = doSomeCalculations()
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM