如何将阴影应用到 HTML5 Canvas 上带圆角的图像

问题描述 投票:0回答:1

我正在开发一个 Web 项目,需要在 HTML5 画布上显示带有圆角的图像。我已经成功实现了圆角效果,但是当我向图像应用阴影时,阴影在角处消失。我希望圆角和阴影效果在图像上同时可见。有人可以提供有关如何在 HTML5 canvas 或节点的 canvas api 上实现此目的的指导或代码吗?

var canvas = document.getElementById ('mycanvas');    // access the canvas object
const background = document.getElementById("source");
const overlay = new Image(300, 300)
overlay.src = 'https://images.unsplash.com/photo-1518826778770-a729fb53327c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1887&q=80';

var context = canvas.getContext ('2d');                             // access the canvas context
const canvasWidth = background.width; // Set your desired width
const canvasHeight = background.height; // Set your desired height


const ctx = canvas.getContext('2d');
   

// Draw the background image
ctx.drawImage(background, 0, 0, background.width, background.height); 


const x = (canvas.width - overlay.width) / 2;
    const y = (canvas.height - overlay.height) / 2;
    ctx.shadowColor = 'rgba(0, 0, 0, 1.0)';
    ctx.shadowBlur = 100;
    ctx.shadowOffsetX = 5;
    ctx.shadowOffsetY = 5;

    // Create a rounded rectangle for the overlay image
    const cornerRadius = 20; // Adjust as needed
    
    ctx.beginPath();
    ctx.moveTo(x + cornerRadius, y);
    ctx.lineTo(x + overlay.width - cornerRadius, y);
    ctx.quadraticCurveTo(x + overlay.width, y, x + overlay.width, y + cornerRadius);
    ctx.lineTo(x + overlay.width, y + overlay.height - cornerRadius);
    ctx.quadraticCurveTo(x + overlay.width, y + overlay.height, x + overlay.width - cornerRadius, y + overlay.height);
    ctx.lineTo(x + cornerRadius, y + overlay.height);
    ctx.quadraticCurveTo(x, y + overlay.height, x, y + overlay.height - cornerRadius);
    ctx.lineTo(x, y + cornerRadius);
    ctx.quadraticCurveTo(x, y, x + cornerRadius, y);
    ctx.closePath();
    ctx.clip();

  

    // Draw the overlay image with the shadow and rounded corners
    ctx.drawImage(overlay, x, y, overlay.width, overlay.height);
<canvas id="mycanvas" width="500" height="500"></canvas>
<div style="display:none;">
  <img id="source" src="https://images.unsplash.com/photo-1534644107580-3a4dbd494a95?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80" width="500" height="500" />
 
  <img id="overlay" src="" width="300" height="300" />
  
</div>

如果图像未加载,请尝试使用您自己的本地图像的代码,提前谢谢您

javascript html canvas html5-canvas node-canvas
1个回答
0
投票

使用 ctx.clip() ,路径之外的所有内容都不会被绘制,这就是图像不会在路径之外绘制的方式,这就是如何获得圆角的方式。但使用该剪辑时,阴影也会出现在角落之外,并且不会被绘制。 所以我要做的是,在剪辑之前,填充路径。然后你就有了一个带有圆角和阴影的填充矩形。之后,在矩形上剪切并绘制图像。 所以直接在

ctx.clip();
命令之前添加
ctx.fill();
希望这有帮助。

而且片段“不起作用”,因为您在浏览器完全加载图像之前就绘制了图像。这就是为什么一切都是白色的。如果您等到图像加载后再开始使用它们会更好。

© www.soinside.com 2019 - 2024. All rights reserved.