HTML5 Canvas

Ken Webb 2011-01-22T12:57:27Z

<script implName="lang:BrowserJS:inline:"><![CDATA[
function drawEllipse(ctx, x, y, w, h) {
  /* http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas/2173084#2173084 */
  var kappa = .5522848;
      ox = (w / 2) * kappa, // control point offset horizontal
      oy = (h / 2) * kappa, // control point offset vertical
      xe = x + w,           // x-end
      ye = y + h,           // y-end
      xm = x + w / 2,       // x-middle
      ym = y + h / 2;       // y-middle
  ctx.beginPath();
  ctx.moveTo(x, ym);
  ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  ctx.closePath();
  ctx.fill();
  ctx.stroke();
};
function drawScene(ctx) {
  /* circle */
  ctx.fillStyle   = 'red';
  ctx.strokeStyle = 'black';
  ctx.lineWidth   = 1;
  ctx.beginPath();
  ctx.arc(30, 50, 20, 0, Math.PI*2, true);
  ctx.fill();
  ctx.stroke();
  ctx.closePath();
  /* rectangle */
  ctx.fillStyle   = 'green';
  ctx.fillRect(150, 50, 50, 40);
  ctx.strokeRect(150, 50, 50, 40);
  /* ellipse */
  ctx.fillStyle   = 'blue';
  drawEllipse(ctx, 240, 20, 100, 40);
  /* text */
  ctx.fillStyle    = 'black';
  ctx.font         = '40px sans-serif';
  ctx.textBaseline = 'middle';
  ctx.fillText  ('Xholon', 120, 130);
  /* line */
  ctx.fillStyle   = 'magenta';
  ctx.strokeStyle = 'magenta';
  ctx.lineWidth   = 5;
  ctx.beginPath();
  ctx.moveTo(45, 50);
  ctx.lineTo(150, 60);
  ctx.stroke();
};
var myCanvas = "" +
"<canvas id='myCan' width='350' height='150'></canvas>" +
"<script type='text/javascript'>" +
"var myCanvas = document.getElementById('myCan');" +
"var ctx = myCanvas.getContext('2d');" +
"drawScene(ctx);" +
"</script>";
$('div#divOne').html(myCanvas);
]]></script>

return to main page