简体   繁体   中英

Square HTML canvas with pure CSS

Let's say I have a HTML canvas with dimensions of 500 x 500. The following CSS code makes a canvas that fills the width and sets the height to the same value, keeping it a square canvas.

canvas {
    width: 100%;
    height: auto;
}

One would think that changing it to the following CSS code would make the canvas fill the height and set an equivalent width, keeping it square. (this would be used in situations like landscape mode)

canvas {
    width: auto;
    height: 100%;
}

But it doesn't. The canvas reverts to the original 500 x 500. Here is a JFiddle example: http://jsfiddle.net/0qp5zkgu/ The canvas in the example is 50 x 50 so its easier to see the difference.

You're going to have to use javascript to set the width and height.

Here's an example::

HTML:

<div id="main" role="main">
    <canvas id="respondCanvas" width="100" height="100">
        < !-- Provide fallback -->
    </canvas>
</div> 

CSS:

#main{
    display:block;
    width:100%;
} 

JS:

$(document).ready( function(){

//Get the canvas & context
var c = $('#respondCanvas');
var ct = c.get(0).getContext('2d');
var container = $(c).parent();

//Run function when browser  resize
$(window).resize( respondCanvas );

function respondCanvas(){
    c.attr('width', $(container).width() ); //max width
    c.attr('height', $(container).width() ); //set the height to the width to make a square

    //Redraw & reposition content
    var x = c.width();
    var y = c.height();             
    ct.font = "20px Calibri";

    ct.fillStyle = "#DDDDDD"; //black
    ct.fillRect( 0, 0, x, y); //fill the canvas

    var resizeText = "Canvas width: "+c.width()+"px";
    ct.textAlign = "center";
    ct.fillStyle = "#333333"; //white
    ct.fillText(resizeText, (x/2), (y/2) );
}

//Initial call
respondCanvas();
});

Fiddle:: http://jsfiddle.net/dp40Lbux/1/

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