FE/Canvas

[ CANVAS ] 이미지 밝기 획득

HEON.D 2023. 6. 9. 13:26
  // 배경 밝기 판정
  getPixelBrightness() {
    const img = new Image();
    img.crossOrigin = `Anonymous`;
    img.src = this.storageUrl + '/' + this.board['selectedBackgroundPath'];

    img.onload = () => {
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');

      canvas.width = img.width;
      canvas.height = img.height;
      context.drawImage(img, 0, 0);

      // const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
      const imageData = context.getImageData(0, 0, canvas.width, 100);
      const data = imageData.data;

      // Get the brightness value of a specific pixel (e.g., at coordinates x=10, y=10)
      const pixelIndex = (10 + 10 * canvas.width) * 4;
      const red = data[pixelIndex];
      const green = data[pixelIndex + 1];
      const blue = data[pixelIndex + 2];
      const brightness = (red + green + blue) / 3;

      this.backgroundBrightness = brightness;
      // console.log('Pixel brightness:', brightness);
    };
  }