Rectangles on canvas - Javascript Canvas

Javascript examples for Canvas:Rectangle

Description

Rectangles on canvas

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> 
      <style id="compiled-css" type="text/css">

body {/*ww  w  . java 2 s  . c  om*/
   background-color: ivory;
}
#canvas {
   border:1px solid red;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var myRect = [];
myRect.push(new Shape(10, 0, 25, 25, "#333"));
myRect.push(new Shape(0, 40, 39, 25, "#333"));
myRect.push(new Shape(0, 80, 100, 25, "#333"));
var currentColor = "orange";
// start
drawAll();
function Shape(x, y, w, h, fill) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.fill = fill;
}
function drawAll() {
    for (var i = 0; i < myRect.length; i++) {
        drawRect(myRect[i]);
    }
}
function drawRect(oRec) {
    context.fillStyle = oRec.fill;
    context.fillRect(oRec.x, oRec.y, oRec.w, oRec.h);
}
// handle mousedown events
function handleMouseDown(e) {
    e.preventDefault();
    var x = parseInt(e.clientX - offsetX);
    var y = parseInt(e.clientY - offsetY);

    for (var i = 0; i < myRect.length; i++) {
        var oRec = myRect[i];
        if (x >= oRec.x && x <= oRec.x + oRec.w && y >= oRec.y && y <= oRec.y + oRec.h) {
            oRec.fill = currentColor;
            drawRect(oRec);
        }
    }
}

$("#canvas").mousedown(function (e) {
    handleMouseDown(e);
});
    });

      </script> 
   </head> 
   <body> 
      <h4>
         Click on a rect to recolor it to 
         <br>
         the current color (orange for this test)
      </h4> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials