CanvasRenderingContext2D.getImageData() returns an ImageData object, which is used to describe the pixel data hidden in the canvas area. This area is represented by a rectangle. The starting point is (sx, sy), the width is sw, and the height is sh.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
canvas {
cursor: crosshair;}
div {
width: 200px; height: 100px;}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div id="hovered-color"></div>
<div id="selected-color"></div>
<script>
var img = new Image();
img.crossOrigin = 'anonymous';
img.src = 'https://imzhangting.github.io/avatar.png';
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 400
canvas.height = 300
img.onload = function() {
ctx.drawImage(img, 0, 0);
img.style.display = 'none';
};
var hoveredColor = document.getElementById('hovered-color');
var selectedColor = document.getElementById('selected-color');
function pick(event, destination) {
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;
destination.textContent = rgba;
return rgba;
}
canvas.addEventListener('mousemove', function(event) {
pick(event, hoveredColor);
});
canvas.addEventListener('click', function(event) {
pick(event, selectedColor);
});
</script>
</body>
</html>