I am trying to get a sprite to show the contents of an H5 canvas element - and then change when the canvas element changes. They way I understand how rendering works in CC and the browser this looks like it should work. The first part of the code works:
// make a canvas element.
var canvas = document.createElement('canvas');
// draw an image on it
var img = new Image();
img.onLoad = onImageDidLoad;
img.src = cc.url.raw('resources/cocos2d.jpg');
// This is what onImageDidLoad looks like:
var onImageDidLoad = function(){
var ctx = canvas.getContext('2d');
ctx.drawImage(img,0,0);
var texture = new cc.Texture2D();
texture.initWithElement(canvas);
// Make a node to show the texture (thats bound to the canvas)
var node = new cc.Node();
var sprite = node.addComponent(cc.Sprite);
node.setContentSize(200,200);
node.setPosition(cc.winSize.width/2,cc.winSize.height.2);
sprite.spriteFrame = new cc.SpriteFrame(texture);
cc.director.getScene().addChild(node);
}
This displays the cocos2d logo in the center of the scene. Yay. But then I try and change it:
onClick: function() {
var img = new Image();
img.onload = function(){
var ctx = canvas.getContext('2d');
ctx.drawImage(img,0,0);
// What do I do here? The sprite doesn't update.
}
img.src = cc.url.raw('resources/cocos2d-x.png');