我有一个遮罩图像。我有质地。应用遮罩后,我要获取此结果并添加阴影。我似乎不知道该怎么做。
您将需要使用另一个画布来保存蒙版的纹理。
// ctx is main canvas context
// mask is image with alpha 1 keeping pixels
// texture is image with texture to mask
// create a canvas and size it and get a 2D context
const masked = document.createElement("canvas");
masked.width = 128;
masked.height = 128;
masked.ctx = masked.getContext("2d");
// draw the texture to the new canvas
masked.ctx.drawImage(texture,0,0,128,128);
// mask it
masked.ctx.globalCompositeOperation = "destination-in";
masked.ctx.drawImage(mask,0,0,128,128);
masked.ctx.globalCompositeOperation = "source-over";
// set the shadow on main canvas
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
ctx.shadowBlur = 5;
// draw the masked texture with shadow
ctx.drawImage(masked, x, y);
// turn off shadow
ctx.shadowColor = "rgba(0, 0, 0, 0)";
每次执行此操作时都不要创建新的画布。如果需要,请重新使用蒙版画布调整大小。