An auto resizing canvas with fixed aspect ratio based on talk of Ethan Marcotte and article at alistapart.
A Pen by Gerhard Preuss on CodePen.
An auto resizing canvas with fixed aspect ratio based on talk of Ethan Marcotte and article at alistapart.
A Pen by Gerhard Preuss on CodePen.
| <div> | |
| <h1>Auto Resize Canvas with fix Aspect Ratio</h1> | |
| <p>Thanks to <a href='http://ethanmarcotte.com/'>Ethan Marcotte</a> for his great talk at <a href='http://2014.beyondtellerrand.com/'>bt2014</a> and this <a href='http://alistapart.com/article/creating-intrinsic-ratios-for-video'>great article</a> by <a href='http://alistapart.com/author/tkoblentz'>Thierry Koblentz</a>. | |
| </div> | |
| <div class='row'> | |
| <div class='col'> | |
| <div class='ratio-wrapper-60p'> | |
| <canvas class='ratio-stretch'> | |
| </canvas> | |
| </div> | |
| </div> | |
| <div class='col'> | |
| <div class='ratio-wrapper-60p'> | |
| <canvas class='ratio-stretch'> | |
| </canvas> | |
| </div> | |
| </div> | |
| </div> |
| $('canvas.ratio-stretch').each(function(index,canvas) { | |
| var resize = function() { | |
| canvas.width = canvas.parentNode.offsetWidth; | |
| canvas.height = canvas.parentNode.offsetHeight; | |
| console.log(canvas.height,canvas.width); | |
| var ctx=canvas.getContext("2d"); | |
| ctx.fillStyle="red"; | |
| ctx.fillRect(0,0,canvas.width, canvas.height); | |
| ctx.clearRect(20,20,canvas.width*0.66666,canvas.height*0.33333); | |
| }; | |
| resize(); | |
| $(window).on('resize orientationchange', resize); | |
| }); |
| .ratio-wrapper-60p { | |
| width: 100%; | |
| padding-top: 60%; | |
| height: 0px; | |
| position: relative; | |
| } | |
| .ratio-stretch { | |
| top: 0px; | |
| left: 0px; | |
| position: absolute; | |
| width: 100%; | |
| height: 100%; | |
| } | |
| .col { | |
| flex-grow: 1; | |
| margin: 10px 10px; | |
| } | |
| .row { | |
| display: flex; | |
| flex-orientation: row; | |
| } |