getImageData returns wrong opacity on the right side of the canvas

Viewed 89

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>

1 Answers

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>

Related