John Smith
John Smith

Reputation: 2341

HTML5 - Canvas, layers, copy

so what I want to achieve is drawing a rectangle with either a color/fillRect or with clearRect and then copy it to the other canvas layer under the one I was drawing on. Also I want to set a background to this layer with opacity.

What I've tried is setting background with fillStyle and fillRect and it went fine. Also I could draw the rectangle with fillRect on the upper canvas which had no background and then copy the rectangle to the other one with drawImage.

Problem was when I tried to create a rectangle with clearRect and copy it. As I noticed I can only clearRect with another rectangle. But then I have to set a background to the upper canvas, which is ok, but when I copy it to the other one it gets darker and darker every time (well of course..)

So how is this possible?

Upvotes: 0

Views: 447

Answers (2)

user1693593
user1693593

Reputation:

When you work with alpha channel you will as you already noticed accumulate alpha channel values as long as alpha < 255. The only way to "reset" this is to start fresh so-to-speak.

Here are a couple of options to get around this -

Option 1

Don't copy anything from the draft canvas to the main canvas but store all points and shapes into a 2-dimensional array or an array consisting of the shape objects with its points, color, line width and so forth.

When you need to update the main canvas, clear both canvases and then re-render all the shapes to the main one.

Option 2

If all shapes on the main canvas is suppose to have the same opacity then use a third off-screen canvas. Draw everything to this canvas non-transparent (this last is important).

When updating main canvas clear it, set globalAlpha on it and then draw the off-screen canvas to it.

Upvotes: 1

ericjbasti
ericjbasti

Reputation: 2075

So we'll probably need some example code, because I'm not 100% sure what your trying to do... your using 2 canvas objects, drawing on the top canvas, and copying that to the bottom canvas... something like?:

 ctx2.drawImage(canvas1,0,0);

then your clearing the top canvas:

 ctx1.clearRect(0,0,canvas1.width,canvas1.height);

and doing your draw routine again? are you trying to get some sort of trail effect or something?

Upvotes: 0

Related Questions