【问题标题】:Can you have multiple clipping regions in an HTML Canvas?您可以在 HTML 画布中有多个剪辑区域吗?
【发布时间】:2011-02-02 19:56:44
【问题描述】:

我有将一堆图像加载到隐藏的 img 元素中的代码,然后是一个 Javascript 循环,它将每个图像放置到画布上。但是,我想剪辑每个图像,使其放在画布上时是一个圆圈。

我的循环如下所示:

    $$('#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();
    });

问题是,只有第一张图像被绘制(或可见)。

如果我删除剪辑逻辑:

    $$('#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);
    });

然后我所有的图像都被绘制出来了。

有没有办法单独剪裁每张图片?

我尝试将剪切区域重置为图像之间的整个画布,但没有奏效。

【问题讨论】:

    标签: javascript html canvas clipping


    【解决方案1】:

    你应该尝试保存当前的上下文状态然后恢复它:

            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
    
            });
    

    我认为当你调用drawImage方法时,你还需要通过添加一个已经在你的avatar.src参数中的源代码将image参数设置为一个Image类。

    您应该查看Canvas State 的参考文档

    【讨论】:

    • 保存/恢复 - 就是这样!太感谢了。不确定您是否建议以不同的方式绘制图像。 te drawimage 代码按照我现在的方式工作正常,使用您提供的代码有什么好处?
    • 这很简单,您不需要将所有图像文件添加到页面中。在 Image() 类中显示源代码就足够了。删除这些文件的好处是让您的页面不会在页面加载时加载这些图像。它是我们正在谈论的页面加载(性能问题)时间:)
    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 2016-04-06
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2013-09-09
    相关资源
    最近更新 更多