你以为它是图片?其实是阴影

60 阅读1分钟

最近看到了一个css boxShadow的一个比较有意思的效果,才知道阴影还能这么玩,来吧,展示。

image.png

首先boxShadow是可以设置多个值得,对,就是用它来画一张图(选择小图,否则浏览器扛不住)

demo:演示地址

  • 代码功能
// 选择文件后生成一张图片
const fileChange = (e) => {
  const file = e.target.files[0];
  const objectURL = URL.createObjectURL(file);
  const img = new Image();
  img.onload = () => {
    generate(img);
  };
  img.src = objectURL;
};

//根据图片渲染对应的canvas,获取像素信息
const generate = async (img) => {
  if (!img) {
    return;
  }
  const canvas = canvasRef.value;
  canvas.width = img.width;
  canvas.height = img.height;
  const ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  // 获取canvas中的位图
  const imageData = ctx.getImageData(0, 0, img.width, img.height).data;
  generateStyle(img.width, img.height, imageData);
  console.log("🚀 ~ file: App.vue:43 ~ generate ~ imageData:", imageData);
};

// 生成对应的style
const generateStyle = (width, height, bmp) => {
  const shadowCssFragment = [];
  // 获取每个像素点
  for (let i = 0; i < height; i++) {
    for (let j = 0; j < width; j++) {
      const m = i * width + j;
      const r = bmp[m * 4];
      const g = bmp[m * 4 + 1];
      const b = bmp[m * 4 + 2];
      const a = bmp[m * 4 + 3] / 255;
      shadowCssFragment.push(`${j + 1}px ${i}px rgba(${r},${g},${b},${a})`);
    }
  }
  boxShadow.value = shadowCssFragment.join(",");
};
结语

不得不说CSS还是牛