Make Html5 Canvas and Its contained image responsive across browsers

后端 未结 2 1444
抹茶落季
抹茶落季 2020-12-17 05:27

I have a canvas object that I want to put an image in for a web application. I can get the image loaded, but I\'ve run into 2 problems: The image won\'t stretch to the canva

相关标签:
2条回答
  • 2020-12-17 05:50

    width and height of image are read-only so that won't work.

    Try instead:

     context.drawImage(image, 0, 0, canvas.width, canvas.height);
    

    This will draw the image the same dimension as the canvas is (you don't need to reload the image every time btw. - just load it once globally and reuse the image variable.)

    0 讨论(0)
  • 2020-12-17 05:58
    <canvas id="imageView" width="1000" height="1000" style="width:100%; height:100%"></canvas>
    

    Both CSS and height and width attributes can be used and do not need to agree in size. The CSS style will determine the displayed size, you asked for a canvas that can stretch. The width and height control the number of pixels the canvas uses for drawing.

    for example this will be scaled 10 to 1, and with anti-aliasing scrolling an drawing in this canvas would be as smooth as silk.

    <canvas id="imageView" width="1000" height="1000" style="width:100px; height:100px"></canvas>
    

    If CSS is not used, their defaults will be the width and height attributes of the canvas element.

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