Canvas How to - Draw rectangle from the canvas center








Question

We would like to know how to draw rectangle from the canvas center.

Answer


<!--  w ww.  j a  va  2 s  .  co  m-->
<!DOCTYPE html>
<html>
<head>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.7.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    var canvas = document.getElementById("squares");
    var ctx = canvas.getContext("2d");
    var centerX = canvas.width / 2;
    var centerY = canvas.height / 2;
    for (var side = 10; side <= 300; side += 10) {
        ctx.strokeRect(centerX - side / 2, centerY - side / 2, side, side);
    }
});//]]>  
</script>
</head>
<body>
  <canvas id="squares" width="320" height="320"></canvas>
</body>
</html>

The code above is rendered as follows: