center a rectangle on a canvas - Javascript Canvas

Javascript examples for Canvas:Rectangle

Description

center a rectangle on a canvas

Demo Code

ResultView the demo in separate window

<html>
   <head></head>
   <body> 
      <canvas id="myCanvas" width="800" height="800" style="border:1px solid #d3d3d3;">
          Your browser does not support the HTML5 canvas tag.
      </canvas> 
      <script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var recWidth = 200//from w w w  . ja  v a2  s . c o  m
var recHeight = 200
var xPos = (document.getElementById("myCanvas").width/2) - (recWidth/2);
var yPos = (document.getElementById("myCanvas").height/2) - (recHeight/2);
ctx.fillRect(xPos,yPos,recWidth,recHeight);

      </script>  
   </body>
</html>

Related Tutorials