HTML5 Canvas distorted?

前端 未结 3 928
抹茶落季
抹茶落季 2020-12-17 10:07

I thought for a bit of fun I would have a look at the canvas. It seemed fairly easy to draw a box so I pretty much copied an example from the mozilla developer site. You can

相关标签:
3条回答
  • 2020-12-17 10:27

    I had the same problem, but I was able to solve it, and include the height and width tags in my css, but I could not used the 'px' unit or '%' on the height or width.

    canvas#my-id{
        width:400;
        height:300;
    }
    

    Whether you use the html tag, css or set it with javascript/jquery etc shouldn't be matter.

    0 讨论(0)
  • 2020-12-17 10:29

    Fixed it myself, I had to set the width and height via the tag, not CSS. Lucky guess.

    <canvas width='400' height='300'></canvas>
    
    0 讨论(0)
  • 2020-12-17 10:33

    Canvas works like an image tag

    A canvas works like an image, it has a width and a height.

    In the case of an image, the browser can work out the width and height by inspecting the file. In the case of a canvas, the width and height cannot be inferred so you must set them directly as attributes.

    <canvas width="400" height="400" />
    

    CSS

    When you set the width using CSS, the height will be adjusted too to maintain the aspect ratio, just like an image. You could set the width to be 100%, and the canvas will fill the container.

    canvas { 
      width:100% 
    }
    

    If you set both the width and height the canvas will be stretched to fit the space you have allocated, just like an image.

    Defaults

    The default width and height of a canvas are 300x150, a 2/1 ratio.

    0 讨论(0)
提交回复
热议问题