Tuesday 28 August 2012

draw html5 canvas element to a master canvas element

I wanted a method where by I could group elements together and then draw that group to my main html5 canvas element.
So from a flash point of view this would be similar to creating an empty moving clip and then using addchild add content to that movieclip.
Then add the movieclip to the stage.


So I found this post....
http://kaioa.com/node/103

I kind of got it... But I'm a little new to javascript and to me it seemed a little bit complicated to having methods sent into other methods.

So I changed it a little for somthing that sits more comfortably in my brain sells!

My code looks like this and was just what I was after...


var canvas;var context;var width;var height;


function domLoaded(e){
canvas = document.getElementById("scroller");
context = canvas.getContext("2d");
width = canvas.getAttribute('width');
height = canvas.getAttribute('height');

var renderToCanvas = function (width, height) {
var buffer = document.createElement('canvas');
var canvasCradle = buffer.getContext("2d");
buffer.width = width;
buffer.height = height;
  canvasCradle.font = "15pt Calibri";
canvasCradle.fillText("Morning all!", 25, 20);
return buffer;
};

var cached = renderToCanvas(150, 25);
context.drawImage(cached, 0, 0);

}
document.addEventListener("DOMContentLoaded", domLoaded);



So on Dom load I GET my canvas element that has an id called scroller from my html markup.

I get its width/hight/context ect and set them to vars.

Now Im ready to create a new canvas element to be drawn to "canvas"

Ive created cached which is equal to the method renderToCanvas
This then creates a new canvas element
I can treat that like any other canvas elements... add what I want to it. I return that canvas element

Cached is now that element I created on the fly and I can now use drawImage on master canvas to draw it to screen.


No comments: