Reputation: 624
I've written the code below which works when creating one canvas object dynamically and filling it with pixels, however when I try to create multiples, it clears the first canvas for some reason. Anybody have any ideas as to why and how to fix it? (JS FIddle doesn't seem to work so somewhat long paste here)
<head>
<script type="text/javascript">
function createnew_canvas()
{
var canvas_number = document.getElementById("hidden_counter").innerHTML.toString();
var new_canvas = parseInt(canvas_number) + 1;
document.getElementById("hidden_counter").innerHTML = new_canvas;
var mydoc = document.getElementById("canvas_area");
var mynewname = "canvas"+ canvas_number.toString();
mydoc.innerHTML = mydoc.innerHTML + '<canvas id="'+ mynewname +'" width="1000" height="600">canvas</canvas><br/>';
draw_canvas(canvas_number);
}
function setPixel(imageData, x, y, r, g, b, a)
{
index = (x + y * imageData.width) * 4;
imageData.data[index+0] = r;
imageData.data[index+1] = g;
imageData.data[index+2] = b;
imageData.data[index+3] = a;
}
function draw_canvas(canvasnum)
{
var myname = "canvas" + canvasnum;
element = document.getElementById(myname);
c = element.getContext("2d");
// read the width and height of the canvas
element.width = document.documentElement.clientWidth ;
element.height = document.documentElement.clientHeight ;
width = element.width;
height = element.height;
// create a new pixel array
imageData = c.createImageData(width, height);
for (i= 0; i < width;i++)
{
for (v =1; v <height - 400; v++)
{
if (i % 12 === 0 )
{
setPixel(imageData, i, 200 + v , 50* canvasnum, 50*canvasnum, 0, 255); // 255 opaque
}
else
{
setPixel(imageData, i, 200 + v, 0, 0, 50*canvasnum, 255); // 255 opaque
}
}
}
c.putImageData(imageData, 0, 0); // at coords 0,0
}
</script>
</head>
<body>
<div class="navbar">
<div class="title">Canvas Maker</div>
<div></div>
<div></div>
<div></div>
<div class="addnewcanvas" onclick="createnew_canvas();"> +</div>
<div id="hidden_counter">1</div>
</div>
<div id="canvas_area"></div>
</body>
Upvotes: 1
Views: 56
Reputation: 103
Append The canvas like this
function createCanvas(id) {
var canvasMade = document.createElement("canvas");
canvasMade.id = id;
document.body.appendChild(canvasMade);
}
Hope this helped...
Upvotes: 1
Reputation: 83729
It looks like you have:
mydoc.innerHTML = mydoc.innerHTML + '<canvas id="'+ mynewname +'" width="1000" height="600">canvas</canvas><br/>';
that will set the html of the element, but doing so will cause any state of the canvas that was there to be lost.
You might want to just try to append your new elements to the mydoc instead of setting the html.
Upvotes: 3