Canvas Html5: multiple canvases and clearing one appears to clear the other canvas as well

html5-canvas, javascript

Solution

You're loading your context from the same canvas object:

var ctx = canvas.getContext( "2d" );
var ctx2 = canvas.getContext( "2d" );

Use this instead:

var ctx = canvas.getContext( "2d" );
var ctx2 = canvas2.getContext( "2d" );

Now the only thing left to wonder is why are you using two canvas instead of just one? It looks like you're trying to overlay them but if you add a border you'll notice that one's on the bottom and the other is on top.

What you really want to do is save your state before drawing one of the objects and then restoring to the previous state.

I've created a new fiddle with an example of using one context (no requestAnimationFrame):

http://jsfiddle.net/z5vtL/1/

Another issue with your code is that you're using setInterval instead of window.requestAnimationFrame. You can find more information at:

https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame

Eh, what the hell, updated JSFiddle to use requestAnimationFrame:

http://jsfiddle.net/z5vtL/3/ (Note the speed property on each object)

Problem

I am trying to draw to different canvas elements and clear them independently. However my 2 different contexts seem to affect both canvas elements and aren't functioning as separate layers. I want to be able to change the different canvas elements independently to create a background and a foreground. Relevant HTML: ``` <canvas id="canvas" style="position: abosloute; top:0px; left: 0px; z-index: 0;" width="500" height="300"></canvas> <canvas id="canvas2" style="position: abosloute; top:0px; left: 0px;z-index: 1;" width="500" height="300"></canvas> ``` Relevant JavaScript (to create the context objects): ``` var canvas = document.getElementById( "canvas" ); var canvas2 = document.getElementById( "canvas2" ); var ctx = canvas.getContext( "2d" ); var ctx2 = canvas.getContext( "2d" ); ``` Relevant JavaScript call: ``` ctx.clearRect( 0, 0, canvas.width, canvas.height ); ``` It appears to clear both `ctx` and `ctx2`. I do not understand why. Here is a link to the complete code on jsfiddle: http://jsfiddle.net/BvMdx/3/

Original source