How to avoid HTML Canvas auto-stretching

前端 未结 5 1555
盖世英雄少女心
盖世英雄少女心 2021-01-01 11:12

I have the following piece of HTML:



&l         


        
相关标签:
5条回答
  • 2021-01-01 11:44

    If you're using JQuery, you shouldn't set the CSS (as the commenters above mentioned). You need to set the attribute so:

    $("canvas").attr('width', aWidth);
    $("canvas").attr('height', aHeight);
    

    works great.

    0 讨论(0)
  • 2021-01-01 11:54

    You need the width and height attributes in the canvas element. They specify the coordinate space for the canvas. Apparently, it defaults to a canvas of a 2:1 aspect ratio, which your CSS is skewing into a square.

    0 讨论(0)
  • 2021-01-01 11:55

    It's worth noting that the Width and Height attributes of canvas are not like the old school <img> width and height attributes. They are not a substitute for CSS. They specify how many pixels the pixel buffer in the canvas itself should have, and if you don't apply a size to it with css, css will imply it's size from that shape of that pixel buffer. Setting the element's size in css does not set the size of the pixel buffer - it resizes it. From a CSS perspective, a <canvas> is entirely the same thing as an <img>.

    0 讨论(0)
  • 2021-01-01 12:02

    Ok, a little bit simplier (and lighter) than JQuery is .. JAVASCRIP ITSELF of course !

    If you need to change dynamicaly your canvas dimensions, just use:

    document.getElementById('yourcanvasid').setAttribute('width', aWidth);
    document.getElementById('yourcanvasid').setAttribute('height', aHeight);
    
    0 讨论(0)
  • 2021-01-01 12:07

    I found it easier to just put a while loop waiting for timeout within my animation loop, For example:

    function animate() {
        c.clearRect(0, 0, window.innerWidth, window.innerHeight);
        ryuji.draw();
        ryuji.update();
        let now = Date.now();
        then = now + (1000 / fps);
        while (Date.now() < then) {
    
        }
        requestAnimationFrame(animate);
    }
    
    0 讨论(0)
提交回复
热议问题