Can you have multiple clipping regions in an HTML Canvas?

后端 未结 1 495
我寻月下人不归
我寻月下人不归 2020-12-16 06:23

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 t

相关标签:
1条回答
  • 2020-12-16 07:02

    You should try to save current context state and then restore it:

            canvas = document.getElementById("area");
            context = canvas.getContext('2d');
    
            $("#avatars img").each(function(avatar) {
    
                var x = Math.floor(Math.random() * canvas.width);
                var y = Math.floor(Math.random() * canvas.height);
    
                context.save();//push current state into canvas
                context.beginPath();
                context.arc(x + 24, y + 24, 20, 0, Math.PI * 2, 1);
                context.clip();
    
                context.strokeStyle = "black";
    
                //draw image this way
                var img = new Image();
                img.src = avatar.src;
                img.onload = function() {
                    context.drawImage(img, x, y);
                };
    
                context.stroke();
                context.restore();//restore context to the state
    
            });
    

    I think when you call drawImage method,you also need to set image parameter as an Image class by adding a source line which is already in your avatar.src parameter.

    You should check the reference document for Canvas State

    0 讨论(0)
提交回复
热议问题