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.
- <div class="row">
- <canvas id="canvas" width=200 height=200 style="min-width:200px;min-height:200px;"></canvas>
- </div>
- <div class="row">
- <div id="containercanvas" style="display:block; float: left;min-width:200px;min-height:200px;background-color:white;">
- <canvas id="canvas" width=200 height=200 style="min-width:200px;min-height:200px;"></canvas>
- </div>
- </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.
- <script type="text/javascript">
- //<![CDATA[
- window.addEventListener('resize', function () {
- canvas.width = 600;
- canvas.height = 600;
- containercanvas.width = 600;
- containercanvas.height = 600;
- }, true);
- //]]>
- </script>
We will resize the square canvas taking into account the width of the window.
- <script type="text/javascript">
- //<![CDATA[
- window.addEventListener('resize', function () {
- var x = window.innerWidth * 0.7;
- x = (x < 200) ? 200 : x;
- canvas.width = x;
- canvas.height = x;
- containercanvas.width = x;
- containercanvas.height = x;
- }, true);
- //]]>
- </script>
Display a drawing in the canvas to check its size adapts accordingly during a resizing of the window.
- <script type="text/javascript">
- //<![CDATA[
- window.addEventListener('resize', function () {
- var x = window.innerWidth * 0.7;
- x = (x < 200) ? 200 : x;
- canvas.width = x;
- canvas.height = x;
- containercanvas.width = x;
- containercanvas.height = x;
- var c = document.getElementById("canvas");
- var ctx = c.getContext("2d");
- ctx.fillStyle = "#00FF00";
- ctx.fillRect(0, 0, x/2, x/2);
- }, true);
- //]]>
- </script>

Jean-Claude ColettePosted Feb 1, 2016, 11:01 AM
Thanks for your comments and likes.
Santhakumar MunuswamyPosted Jan 30, 2016, 2:49 AM
Thanks for nice share
Shubham KumarPosted Jan 21, 2016, 4:04 AM
thnx for the info
Jaco ZwartsPosted Jan 18, 2016, 12:39 AM
Nice Article!