Barry Briggs
Barry Briggs

Reputation: 209

Stacking canvases and transparency

Two canvases one on top of the other as below. The second canvas cvs should be transparent since by default all canvases are transparent and I do a clearRect just to make sure.

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="430"></canvas>
    <canvas id="cvscan" style="display:none"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var cvs = document.getElementById('cvscan');
        var cvsctx = cvs.getContext('2d');

        context.save();
        context.clearRect(0, 0, 578, 430);
        context.fillStyle = 'gray';
        context.fillRect(0, 0, 578, 430);

        context.beginPath();
        context.moveTo(0, 0);
        context.lineWidth = 3;
        context.lineTo(578, 430);
        context.strokeStyle = '#444444';
        context.stroke();

        context.moveTo(578, 0);
        context.lineTo(0, 430);
        context.stroke();

        cvs.width = 200;
        cvs.height = 200;
        cvsctx.clearRect(0, 0, cvscan.width, cvscan.height);
        var curimg = cvsctx.getImageData(0, 0, cvs.width, cvs.height);
        context.putImageData(curimg, 50, 50);

        context.restore();
    </script>
</body>
</html>

I believe the second canvas should be transparent and (since there's nothing drawn in it) invisible -- but it's filled with white. What am I missing?

UPDATE this is what I see -- I believe the white box should not be there.

Here is the image

Upvotes: 0

Views: 62

Answers (1)

user1044800
user1044800

Reputation:

The canvas with id="cvscan" is being cleared, which means the image data is being set to 0 for all, rgba(0,0,0,0), values.

Next, that image data is being painted onto the canvas with id="myCanvas", updating the pixel on "myCanvas" to zero.

So, the canvas ("myCanvas") is now transparent at the painted location, and is seen as white, because the background of the body is now showing.

To validate the results a test was run logging the data of the image, and then updating bgcolor to red.

(see photos) enter image description here

enter image description here

Upvotes: 1

Related Questions