I'm trying to get the opacity of a gradient of the mouse position when it's over a canvas. However when the mouse is close to the right edge returns 0 instead of 255.
This behavior seems to change on different sizes. On small sizes the opacity returned doesn't reach 255.
How i can get the correct opacity regardless the size?
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d", { alpha: true});
const gradient = context.createLinearGradient( 0, 0 , canvas.width, 0);
gradient.addColorStop( 0, "rgba(0, 0, 0, 0)" );
gradient.addColorStop( 1, "rgba(0, 0, 0, 1)" );
context.fillStyle = gradient;
context.fillRect( 0, 0, canvas.width, canvas.height);
canvas.addEventListener("mousemove", function() {
const p = document.getElementById("result");
const x = event.offsetX;
const y = event.offsetY;
const imageData = context.getImageData( x, y, 1, 1)
p.textContent = imageData.data;
})
#canvas {
width: 100%;
height: 30px;
}
#result {
margin-top: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id="canvas"></canvas>
<p id="result"></p>
</body>
</html>