ASP.NET MVC - Responsive Canvas

After we have created a ASP.NET MVC  application with Visual Studio, we can insert our canvas in the homepage Index.cshtml  in the Home subdirectory of Views.

In order to do not have other objects to the sides of the canvas, we will place it in a container div of class row of Bootstrap. This is the code.

  1. <div class="row">  
  2.    <canvas id="canvas" width=200 height=200 style="min-width:200px;min-height:200px;"></canvas>  
  3. </div>  
But we will not see the canvas, since by default, there is no background. For this reason, we are going to add a container div wrapped around the canvas.
  1. <div class="row">  
  2.    <div id="containercanvas" style="display:block; float: left;min-width:200px;min-height:200px;background-color:white;">  
  3.       <canvas id="canvas" width=200 height=200 style="min-width:200px;min-height:200px;"></canvas>  
  4.    </div>  
  5. </div>  

For the moment, the canvas has a fixed size of 200 x 200 and is not auto-resizable.

To make it resizable, let's catch the window resize event and add to the event handler a function enlarging the canvas, and the containercanvas block.

  1. <script type="text/javascript">  
  2. //<![CDATA[  
  3.    window.addEventListener('resize', function () {  
  4.       canvas.width = 600;  
  5.       canvas.height = 600;  
  6.       containercanvas.width = 600;  
  7.       containercanvas.height = 600;  
  8.    }, true);  
  9. //]]>  
  10. </script>  

We will resize the square canvas taking into account the width of the window.

  1. <script type="text/javascript">  
  2. //<![CDATA[  
  3.    window.addEventListener('resize', function () {  
  4.       var x = window.innerWidth * 0.7;  
  5.       x = (x < 200) ? 200 : x;  
  6.       canvas.width = x;  
  7.       canvas.height = x;  
  8.       containercanvas.width = x;  
  9.       containercanvas.height = x;  
  10.    }, true);  
  11. //]]>  
  12. </script>  

Display a drawing in the canvas to check its size adapts accordingly during a resizing of the window.

  1. <script type="text/javascript">  
  2. //<![CDATA[  
  3.    window.addEventListener('resize', function () {  
  4.       var x = window.innerWidth * 0.7;  
  5.       x = (x < 200) ? 200 : x;  
  6.       canvas.width = x;  
  7.       canvas.height = x;  
  8.       containercanvas.width = x;  
  9.       containercanvas.height = x;  
  10.       var c = document.getElementById("canvas");  
  11.       var ctx = c.getContext("2d");  
  12.       ctx.fillStyle = "#00FF00";  
  13.       ctx.fillRect(0, 0, x/2, x/2);  
  14.    }, true);  
  15. //]]>  
  16. </script>  
Ebook Download
View all
Learn
View all