Quantcast
Viewing latest article 1
Browse Latest Browse All 10

A complex canvas example

In the previous post we saw about canvas using path and also using rectangles in this example we will see how to combine them to form a complex and at the same time an interesting composition.

Image may be NSFW.
Clik here to view.

<html>
  <head>
   <script type="application/javascript">
 function drawBowtie(ctx, fillStyle) {

   ctx.fillStyle = "rgba(200,200,200,0.3)";
   ctx.fillRect(-30, -30, 60, 60);

   ctx.fillStyle = fillStyle;
   ctx.globalAlpha = 1.0;
   ctx.beginPath();
   ctx.moveTo(25, 25);
   ctx.lineTo(-25, -25);
   ctx.lineTo(25, -25);
   ctx.lineTo(-25, 25);
   ctx.closePath();
   ctx.fill();
 }

 function dot(ctx) {
   ctx.save();
   ctx.fillStyle = "black";
   ctx.fillRect(-2, -2, 4, 4);
   ctx.restore();
 }

 function draw() {
   var canvas = document.getElementById("canvas");
   var ctx = canvas.getContext("2d");

   // note that all other translates are relative to this
   // one
   ctx.translate(45, 45);

   ctx.save();
   //ctx.translate(0, 0); // unnecessary
   drawBowtie(ctx, "red");
   dot(ctx);
   ctx.restore();

   ctx.save();
   ctx.translate(85, 0);
   ctx.rotate(45 * Math.PI / 180);
   drawBowtie(ctx, "green");
   dot(ctx);
   ctx.restore();

   ctx.save();
   ctx.translate(0, 85);
   ctx.rotate(135 * Math.PI / 180);
   drawBowtie(ctx, "blue");
   dot(ctx);
   ctx.restore();

   ctx.save();
   ctx.translate(85, 85);
   ctx.rotate(90 * Math.PI / 180);
   drawBowtie(ctx, "yellow");
   dot(ctx);
   ctx.restore();
 }
    </script>
  </head>
  <body onload="draw()">
    <canvas id="canvas" width="300" height="300"></canvas>
  </body>
 </html>

In the above example we can find two methods drawbowtie and dot both these methods are called 4 times each .And the calls like translate() ,rotate() are used to set transformation matrix which in turn positions the dot and the bowtie .dot function is used to place the small black square at (0,0) .That dot is moved around by the transformation matrix .drawBowtie will create a very simple bowtie path using the passed-in fill style.
The functions save() and restore() are used to set the original canvas state.This rotation always occur around the current origin.Thus a translate() rotate() translate() sequence will yield different results than a translate() translate() rotate() series of calls.

Image may be NSFW.
Clik here to view.
DZone
Image may be NSFW.
Clik here to view.
StumbleUpon
Image may be NSFW.
Clik here to view.
Digg
Image may be NSFW.
Clik here to view.
Share


Viewing latest article 1
Browse Latest Browse All 10

Trending Articles