Can you have multiple clipping regions in an HTML Canvas?

Posted by emh on Stack Overflow See other posts from Stack Overflow or by emh
Published on 2010-03-31T08:22:31Z Indexed on 2010/03/31 11:23 UTC
Read the original article Hit count: 307

Filed under:
|
|
|

I have code that loads a bunch of images into hidden img elements and then a Javascript loop which places each image onto the canvas. However, I want to clip each image so that it is a circle when placed on the canvas.

My loop looks like this:

    $$('#avatars img').each(function(avatar) {
        var canvas = $('canvas');
        var context = canvas.getContext('2d');

        var x = Math.floor(Math.random() * canvas.width);
        var y = Math.floor(Math.random() * canvas.height);

        context.beginPath();
        context.arc(x+24, y+24, 20, 0, Math.PI * 2, 1);
        context.clip();

        context.strokeStyle = "black";

        context.drawImage(document.getElementById(avatar.id), x, y);

        context.stroke();
    });

Problem is, only the first image is drawn (or is visible).

If I remove the clipping logic:

    $$('#avatars img').each(function(avatar) {
        var canvas = $('canvas');
        var context = canvas.getContext('2d');

        var x = Math.floor(Math.random() * canvas.width);
        var y = Math.floor(Math.random() * canvas.height);

        context.drawImage(document.getElementById(avatar.id), x, y);
    });

Then all my images are drawn.

Is there a way to get each image individually clipped?

I tried resetting the clipping area to be the entire canvas between images but that didn't work.

© Stack Overflow or respective owner

Related posts about html

Related posts about canvas