简体   繁体   English

你可以在HTML Canvas中有多个剪辑区域吗?

[英]Can you have multiple clipping regions in an HTML Canvas?

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. 我有一些代码将一堆图像加载到隐藏的img元素中,然后是一个Javascript循环,将每个图像放到画布上。 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. 我尝试将剪切区域重置为图像之间的整个画布,但这不起作用。

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 . 我想当你调用drawImage方法时,你还需要通过添加一个已存在于avatar.src参数中的源代码行将image参数设置为Image类。

You should check the reference document for Canvas State 您应该查看Canvas State的参考文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM