我正在尝试在使用 Fabric JS 添加到 Canvas 的图像周围创建笔划。我添加到具有透明背景的 PNG 中的笔画如下所示:
尽管我试图在图像“周围”创建笔划并将笔划粘贴到图像的边缘,但 Fabric JS 只是创建了一个“方形”笔划。
我怎样才能完成“围绕”图像的描边,有什么想法吗? 我似乎找不到任何文档或演示来完成我正在尝试做的事情。
谢谢
最佳答案
只需几步即可完成。
- 将 png 图像上传到 Canvas
- 添加“贴纸描边效果”(来自this article)
// this._ctx = context of canvas
this._ctx.shadowColor = '#fff';
this._ctx.shadowBlur = 3;
this._ctx.shadowOffsetX = 0;
this._ctx.shadowOffsetY = 0;
this._ctx.drawImage(img, 30, 30, img.width, img.height);
// get contents of blurry bordered image
const imgData = this._ctx.getImageData(
0,
0,
this._ctx.canvas.width - 1,
this._ctx.canvas.height - 1
);
const opaqueAlpha = 255;
// turn all non-transparent pixels to full opacity
for (let i = imgData.data.length; i > 0; i -= 4) {
if (imgData.data[i + 3] > 0) {
imgData.data[i + 3] = opaqueAlpha;
}
}
// write transformed opaque pixels back to image
this._ctx.putImageData(imgData, 0, 0);
this._ctx.shadowColor = '#aaa';
this._ctx.shadowBlur = 3;
this._ctx.shadowOffsetX = 0;
this._ctx.shadowOffsetY = 0;
this._ctx.drawImage(this._canvas, 0, 0);
- 将数据导出到 base64 并通过 fabric 粘贴
// you can export your image to data url
const url = this._canvas.toDataURL();
// and you can add image from data url to fabric
fabric.Image.fromURL(url, oImg => {
this._cf.add(oImg);
});
它会工作,但为了更好的用户体验,你应该考虑如何动态地做(我现在正在研究),我的意思是:用户添加图像,你想让他选择“中风” “或者不等等等等......
关于fabricjs - Fabric JS 中自定义图像的描边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56264312/