Auto-resizing background image using Canvas


/ Published in: JavaScript
Save to your folder(s)

The canvas drawImage size default is 300 x 150, so it's using the CSS to resize the canvas. Example posted at http://pastebin.me/76aed7005b1b413ea3c479287f4dbd59


Copy this code and paste it in your HTML
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>Conforming XHTML 1.0 Strict Template</title>
  6. </head>
  7. <body>
  8.  
  9. <h2>Auto-resizing the background image using Canvas</h2>
  10.  
  11. <canvas id="myCanvas" style="width: 100%; height: 100%; position: absolute; left: 0px; top: 0px; z-index: -1;"></canvas>
  12. <script type="text/javascript">
  13. var context = document.getElementById('myCanvas').getContext('2d');
  14. var w = document.body.clientWidth;
  15. var h = document.body.clientHeight;
  16. img = new Image();
  17. img.src='http://i201.photobucket.com/albums/aa236/Mottie1/testsite/screenshots/bg1.jpg';
  18. img.onload = function () {
  19. context.drawImage(this,0,0,300,150);
  20. };
  21. </script>
  22. </body>
  23. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.