Reputation: 1879
Look: http://jsfiddle.net/MrHIDEn/QYL3t/
This code draws 3 boxes Reg,Green,Blue but context("2d") from Blue does do nothing. Why?
HTML:
<div id="divR">
<canvas id="cvsR" width="100" height="100" style="border:1px solid red"></canvas>
</div>
<div id="divG"></div>
<div id="divB"></div>
Javascript:
var cvsR = document.getElementById("cvsR");
var ctxR = cvsR.getContext("2d");
ctxR.fillStyle = "red";
ctxR.fillRect(0, 0, 50, 75);
var divG = document.getElementById("divG");
divG.innerHTML = '<canvas id="cvsG" width="100" height="100" style="border:1px solid green"></canvas>';
var cvsG = document.getElementById("cvsG");
var ctxG = cvsG.getContext("2d");
ctxG.fillStyle = "green";
ctxG.fillRect(0, 0, 50, 75);
// Dynamiclly
var divB = document.getElementById("divB");
var cvsB = document.createElement("canvas");
cvsB.width = 100;
cvsB.height = 100;
cvsB.style.border = "1px solid blue";
cvsB.id = "cvsB";
var ctxB = cvsB.getContext("2d");
ctxB.fillStyle = "blue";
ctxB.fillRect(0, 0, 50, 75);
divB.innerHTML = cvsB.outerHTML;
Upvotes: 1
Views: 492
Reputation: 19367
I would append the canvas before reading the context, but it works without this, so this is just my personal preference:
cvsB.id = "cvsB";
divB.appendChild(cvsB);
var ctxB = cvsB.getContext("2d");
ctxB.fillStyle = "blue";
ctxB.fillRect(0, 0, 50, 75);
Upvotes: 1
Reputation: 97672
Your problem is here divB.innerHTML = cvsB.outerHTML;
, with this code you aren't adding the canvas cvsB
to divB but a can vas with the same html as cvsB
. To add cvsB
to the div just append it
divB.appendChild(cvsB);
Upvotes: 4