javascript - 重叠剪裁问题
问题描述
我有一个问题,我要抓住一个用户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();
解决方案
看一下画布 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>
推荐阅读
- reactjs - 如果没有使用 Typescript 传递给 NextJS 中的功能组件,如何设置道具的默认值
- javascript - 在同一点击中创建和拖动
- database - Wordpress 插件将数据添加到数据库,然后调用数据
- go - 如何缓存一个 TCP 反向代理数据传输?
- scala - ScalaJs + ZIO:程序适用于 sbt 1.2.8 但不是 >= 1.3
- swift - 如何在 Swift 中设置计时器?
- python - 无法在使用 selenium 和 python 的谷歌会议中点击“要求加入”
- javascript - 解密使用 javascript:void(0) 隐藏的 href 链接
- c# - 如何仅在玩家移动时使对象移动
- macos - Docker 桌面不启动 (Mac Big Sur)