HTML5 Canvas




CV.js, June 19 2013

Michael Holroyd

What is <canvas>?


"HTML element for a resolution dependent bitmap canvas"
i.e. A rectangle you can draw stuff onto with Javascript.


Well support by essentially all browsers except
Internet Explorer 8 and earlier

How to draw

<html>
<body>
  <canvas width=512 height=512 id='myCanvas'></canvas>
<body>
<script>
  var ctx = document.getElementById("myCanvas").getContext("2d");
  ctx.fillRect(50, 100, 400, 300);
<script>
<html>


  for (var x = 0.5; x < canvas.width; x += 10) {
    ctx.moveTo(x, 0);
    ctx.lineTo(x, canvas.height);
  }
  for (var y = 0.5; y < canvas.height; y += 10) {
    ctx.moveTo(0, y);
    ctx.lineTo(canvas.width, y);
  }
  ctx.strokeStyle = "#eee";
  ctx.stroke();

Really though...



Drawing directly to the canvas is roughly as painful as writing raw postscript.


Make your graphics in a proper editor, load as an SVG, then animate them with js.


Two example apps from Arqball

 


Demo the Editor:




Arqspin.com interactive web-based editor

Basic Idea:

var refreshrate = 1000 / 30.0; setInterval(nextFrame, refreshrate);

function nextFrame() { var position += (30 / 1000) * spinspeed; var idx = Math.floor(position * nImages); paint(imgs[idx]); }

function paint(img) { var ctx = document.getElementById('c').getContext('2d');

ctx.drawImage(img,crop_x,crop_y,crop_w,crop_h,0,0,canvasWidth,canvasWidth);

var d = ctx.getImageData(0,0,canvasWidth, canvasWidth); for(var i = 0; i < d.data.length; i+=4) { var greyScale = ( d.data[i+0]+d.data[i+1]+d.data[i+2] ) / 3; for(var c = 0; c < 3; c++) { d.data[i+c] = colorMap(brightness,saturation,contrast,wp,bp,greyScale); } } }

Demo the Gallery:




Focustwist.com live feed on tumblr



Basic Idea:

var imgidx = 0;

var focuskey = new Image(); focuskey.onload = arqfocinit; focuskey.src = server+id+"/focus.png";

function arqfocinit() { var canvas = document.createElement("canvas"); var fkey = canvas.getContext("2d"); fkey.drawImage(focuskey, 0, 0, 512, 512);

var draw_canvas = document.getElementById("c"); drawctx = draw_canvas.getContext("2d"); drawctx.globalAlpha=0.2; //cross-fade for free!

setInterval(draw,50); }

function draw() { if(img[imgidx] && img[imgidx].complete) drawctx.drawImage(img[imgidx],0,0); }

Thanks


Tutorials:
http://diveintohtml5.info/canvas.html

Arqball:
http://arqspin.com
http://focustwist.com

Michael Holroyd
http://meekohi.com

HTML5 Canvas

By Michael Holroyd

HTML5 Canvas

  • 2,779