【问题标题】:Overlapping clipping issue重叠剪裁问题
【发布时间】:2019-10-13 07:42:24
【问题描述】:

我遇到了一个问题,我正在抓取用户 displayAvatar(),然后我使用弧线使图像变圆。这很好用,但是,我需要在该图像上放置一个圆圈,但由于之前的clip()

,它被切成了两半

没有clip()https://i.gyazo.com/b474c656f33a1f004f5e3becffcef527.png

clip() : https://i.gyazo.com/da13377cd3f6dc7516c2b8fd1f0f8ac9.png

我知道在“使用剪辑()”图像中,弧形边框似乎显示在剪辑之外,但这是硬编码到图像中的,我将其作为图像编辑器的指南。

我尝试在代码中移动,我删除了 ctx.clip() 行,发现我的圆圈在图像顶部显示良好。

        // circle around avatar
        ctx.beginPath();
        ctx.arc(122.5, 141.8, 81, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.clip();
        const avatar = await Canvas.loadImage(
            message.author.displayAvatarURL({ format: 'png' })
        );
        ctx.strokeStyle = '#ffffff';
        ctx.strokeRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(avatar, 41.5, 60.5, 162, 162);

        // presence circle
        ctx.beginPath();
        ctx.arc(184.5, 193.5, 19, 0, Math.PI * 2, true);
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = 8;
        ctx.stroke();
        ctx.fillStyle = userStatusColor;
        ctx.fill();

【问题讨论】:

    标签: javascript node.js canvas discord.js node-canvas


    【解决方案1】:

    看看canvas的clip()定义:
    https://www.w3schools.com/tags/canvas_clip.asp

    提示:一旦某个区域被剪裁,以后所有的绘图都将被限制在被剪裁的区域内(无法访问画布上的其他区域)。但是,您可以在使用 clip() 方法之前使用 save() 方法保存当前画布区域,并在将来的任何时间恢复它(使用 restore() 方法)。

    以下是使用保存和恢复的示例

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    
    ctx.beginPath();
    ctx.arc(90, 90, 81, 0, Math.PI * 2, true);
    ctx.stroke();
    
    ctx.save();
    ctx.clip();
    
    ctx.beginPath();
    ctx.arc(150, 50, 19, 0, Math.PI * 2, true);
    ctx.fillStyle = '#0000ff';
    ctx.lineWidth = 8;
    ctx.stroke();
    ctx.fill();
    
    ctx.restore();
    
    ctx.beginPath();
    ctx.arc(170, 99, 19, 0, Math.PI * 2, true);
    ctx.fillStyle = '#ff0000';
    ctx.lineWidth = 8;
    ctx.stroke();
    ctx.fill();
    <canvas id="canvas"></canvas>

    【讨论】:

    • 谢谢!我实际上确实尝试过ctx.save();,但我没有完全理解它,并且从未尝试过ctx.restore();
    猜你喜欢
    • 2022-12-10
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 2013-03-05
    • 2013-11-03
    相关资源
    最近更新 更多