Skip to content Skip to sidebar Skip to footer

Canvas Inside Canvas Of Html5

Can we place a canvas inside the existing canvas?If we can,please help to do it in html5.

Solution 1:

There are two possible ways to interpret your question. One is that you mean to actually nest canvas elements themselves, like this:

<canvas id="outer">
    <canvas id="inner"></canvas>
</canvas>

This is legal (according to validator.nu) but pointless. The content inside the canvas element is for fallback. The only way the content inside the canvas element gets used is if the browser doesn't support canvas, in which case the inner canvas element won't be seen anyway.

The other possible way to interpret your question is can you display the image shown on one canvas within another. This is quite straightforward, a canvas element can be used as the first parameter to context.drawImage(). If you have two canvas elements:

<canvas id="c1" width="200" height="200"></canvas>
<canvas id="c2" width="200" height="200"></canvas>

Then this script (using jQuery) will draw on the first canvas and then add that four times as an image to the second canvas:

var c1 = $('#c1');
var ctx1 = c1[0].getContext('2d');

ctx1.fillRect(50,50,100,100);

var c2 = $('#c2');
var ctx2 = c2[0].getContext('2d');

ctx2.drawImage(c1[0],0,0,100,100);
ctx2.drawImage(c1[0],100,0,100,100);
ctx2.drawImage(c1[0],0,100,100,100);
ctx2.drawImage(c1[0],100,100,100,100);

But again, why would you? You can replicate the image of the second canvas above just using one:

var c1 = $('#c1');
var ctx1 = c1[0].getContext('2d');

ctx1.fillRect(25,25,50,50);
ctx1.fillRect(125,25,50,50);
ctx1.fillRect(25,125,50,50);
ctx1.fillRect(125,125,50,50);

So in summary: yes, it's possible, but it's not really necessary in simple use.

Solution 2:

It would be absolutely pointless to nest a canvas inside of another canvas. The page only sees what is inside the canvas tag if the browser doesn't support the canvas. So, just do what robertc said: <canvas id="background">fallbacks/polyfills go in here...</canvas> <canvas id="foreground">.. or here, but not other canvases.</canvas>

Post a Comment for "Canvas Inside Canvas Of Html5"