要在JavaScript的Canvas中创建凸起、凹陷和雕刻效果的矩形,可以使用以下方法:

  1. 凸起效果:
    • 使用fillRect()绘制一个矩形。
    • 使用shadowOffsetXshadowOffsetY属性来设置阴影的偏移量。
    • 使用shadowBlur属性来设置阴影的模糊程度。
    • 使用shadowColor属性来设置阴影的颜色。
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "red";
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 5;
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
ctx.fillRect(50, 50, 200, 100);
  1. 凹陷效果:
    • 使用fillRect()绘制一个矩形。
    • 使用shadowOffsetXshadowOffsetY属性来设置阴影的偏移量。
    • 使用shadowBlur属性来设置阴影的模糊程度。
    • 使用shadowColor属性来设置阴影的颜色。
    • 使用globalCompositeOperation属性将绘制模式设置为source-atop,以便绘制的内容只在矩形内部可见。
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "red";
ctx.shadowOffsetX = -5;
ctx.shadowOffsetY = -5;
ctx.shadowBlur = 5;
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
ctx.fillRect(50, 50, 200, 100);

ctx.globalCompositeOperation = "source-atop";
ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
ctx.fillRect(50, 50, 200, 100);
  1. 雕刻效果:
    • 使用fillRect()绘制一个矩形。
    • 使用shadowOffsetXshadowOffsetY属性来设置阴影的偏移量。
    • 使用shadowBlur属性来设置阴影的模糊程度。
    • 使用shadowColor属性来设置阴影的颜色。
    • 使用globalCompositeOperation属性将绘制模式设置为destination-out,以便绘制的内容只在矩形外部可见。
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "red";
ctx.shadowOffsetX = 5;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 5;
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
ctx.fillRect(50, 50, 200, 100);

ctx.globalCompositeOperation = "destination-out";
ctx.fillRect(50, 50, 200, 100);

这些方法可以根据需要进行调整,例如改变颜色、阴影的参数等,以实现不同的效果

js canvas 矩形做凸起凹陷雕刻

原文地址: https://www.cveoy.top/t/topic/ibaZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录