getImageData returns wrong opacity on the right side of the canvas

Just to add a working snippet with the solution.

As @ibrahimmahrir said at the comment section above. The problem was the fact that i had to convert X coordinates relative to the canvas on the DOM.

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 * this.width / this.offsetWidth;
  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>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top