Pick Color From Image Using Canvas In Angular

We’ll learn how to pick a color when the mouse hovers over an image in this article.

An image element was constructed to represent the picture that would be drawn on the canvas. Alternatively, we might utilize JavaScript’s Image object.

Introduction:

Pick color from image is work same as color picker.

You may edit pixel data directly using the ImageData object by reading and writing a data array.

1) Draw image on canvas

Adding images to a canvas is essentially a two-step procedure:

  1. As a source, get a reference to an HTMLImageElement object or another canvas element. Alternatively, you may utilize photos by providing a URL.

2. Use the drawImage() method to draw the image on the canvas.

2) Get color from Image

The ImageData object represents the underlying pixel data of a canvas object’s region. It has the following read-only properties:

  •   width
    The width of the image in pixels.
  •   height
    The height of the image in pixels.
  •    data
    The data property provides an Uint8ClampedArray that may be used to inspect the raw pixel data, each pixel is represented by four one-byte values(red, green, blue, and alpha).

Now, let’s start coding for this.

create new project in angular with following command.

ng g new <projectname>

Remove code from the app.component.html file and add copy the following code and paste into it.

<div class="container">
  <div class="row mt-4 ">
    <div class="col-5 image">
      <canvas id="canvas" width="460" height="480"></canvas>
    </div>
    <div class="col-1"></div>
    <div class="col-2 mt-4">
      <h5>Color on hover</h5>
      <div id="hovered-color" class="image-color"></div><br /><br />
      <h5>Color on click</h5>
      <div id="selected-color" class="image-color"></div>
    </div>
    <div class="col-3">
      <div id="rgba-color" class="color-content"></div>
      <div id="hexa-color" class="color-content"></div><br /><br />
      <div>
        <input type="file" id="file" (change)="handleImage($event)"/>
      </div>
    </div>
  </div>
</div>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ImageColorPicker';
  public canvas: any;
  public rgb: any;
  ngOnInit() {
    var img = new Image();
    img.src = './assets/image2.png';

    this.canvas = document.getElementById('canvas');
    var ctx = this.canvas.getContext('2d');

    img.onload = function () {
      ctx.drawImage(img, 15, 15, self.canvas.width, self.canvas.height);
      img.style.display = 'none';
    };

    var hoveredColor = document.getElementById('hovered-color');
    var selectedColor = document.getElementById('selected-color');

    this.canvas.addEventListener('mousemove', (event: any) => {
      this.pick(event, hoveredColor);
    });
    this.canvas.addEventListener('click', (event: any) => {
      var rgba = document.getElementById('rgba-color') as HTMLElement;
      var hexa = document.getElementById('hexa-color') as HTMLElement;
      var data = this.pick(event, selectedColor);
      const rgb = `rgba(${data[0]}, ${data[1]}, ${data[2]}, ${data[3] / 255})`;
      rgba.textContent = rgb;

      const hex = "#" + ("000000" + this.rgbToHex(data[0], data[1], data[2])).slice(-6);
      hexa.textContent = hex;
    });

  }
  rgbToHex(r: any, g: any, b: any) {
    if (r > 255 || g > 255 || b > 255)
      throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
  }
  pick(event: any, destination: any) {
    var ctx = this.canvas.getContext('2d');
    var x = event.layerX;
    var y = event.layerY;
    var pixel = ctx.getImageData(x, y, 1, 1);
    var data = pixel.data;
    const rgba = `rgba(${data[0]}, ${data[1]}, ${data[2]}, ${data[3] / 255})`;
    destination.style.background = rgba;
    return data;
  }
  handleImage(e: any) {
    var ctx = this.canvas.getContext('2d');
    var reader = new FileReader();
    reader.onload = function (event: any) {
      var img = new Image();
      img.onload = function () {

        ctx.drawImage(img, 15, 15, self.canvas.width, self.canvas.height);
      }
      img.src = event.target.result;
    }
    reader.readAsDataURL(e.target.files[0]);

  }
}
declare global {
  interface Window {
    canvas: any;
  }

}

Here, to display the color under the mouse pointer, we utilize the getImageData() function.

We require the current mouse location with layerX and layerY for this, then we seek for the pixel data for that point in the pixel array provided by getImageData().

We use a background color using the array data and show the color with text in the <div>.

app.component.css

.image{
    background: #fff;
    -webkit-transition: all 0.2s ease;
    transition: all 0.2s ease;
    border-radius: 5px;
    box-shadow: 0 13px 13px rgb(0 0 0 / 20%);
    box-sizing: border-box;
    color: #000;
    background-color: #fff;
    border: 1px solid transparent;
    width: 490px;
    height: 490px;
    padding: 0;
    margin: 0;
}
.color-content{
    border:1px solid #bbaeae;
    color:#856d6d;
    border-radius: 10px;
    text-align: center;
    height:40px;
    margin-left:10px;
    margin-top:50px;
    padding:7px;
}
.image-color{
    height:80px;
    border-radius: 11px;
}

Output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories