0

On what are seemingly random occasions, the color of HTML canvas elements appear lighter than they are actually supposed to be. In the code snippet below, I set both the outline and fill to "red", which is supposed to be a valid CSS color corresponding to #ff0000, but under close inspection, the color of the outline is #ff8080. Why does this happen?

image of the outline being lighter than the solid filled in color image 2 of the outline being lighter than the solid filled in color

In addition, while the reproducible example was only on a outline, I initially saw this happen when I tried to create a black rectangle (#000) and it was gray. (#808080)

Is there a canvas context setting for this? Perhaps a rendering error?

render()

function render() {

  var canvas = document.createElement("canvas")
  
  canvas.width = 100
  canvas.height = 100
  
  console.log("created canvas",canvas)

  // CREATE CONTEXT
  var context = canvas.getContext("2d")
  console.log("created context",context)

  context.strokeStyle = "red"
  context.strokeRect(10,10,50,50)

  context.fillStyle = "red"
  context.fillRect(12.5,12.5,45,45)
  
  document.body.appendChild(canvas)
}
Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34
  • It might be the tool you are using to see what color is present right now, color picker tools produce this kind of problems sometimes. Maybe you can try this tool on other kinds of HTML elements colors and see if it is accurate and if so, please add those details to your question as well just to be more precise. – Agil Atakishiyev Aug 07 '22 at 07:33

1 Answers1

0

The Problem is Anti-Aliasing. The line is drawn between two pixels and therefor only half as bright on each of them. If you want a crisp edge, you need to draw it at 0.5 pixel offsets, see below. With rects it is exactly the opposite. I don't know how portable it is, so you might need to experiment.

render()

function render() {

  var canvas = document.createElement("canvas")
  
  canvas.width = 100
  canvas.height = 100
  
  console.log("created canvas",canvas)

  

  // CREATE CONTEXT
  var context = canvas.getContext("2d")
  console.log("created context",context)


  context.strokeStyle = "red"
  context.strokeRect(10.5,10.5,50,50)

  context.fillStyle = "red"
  context.fillRect(12,12,45,45)

  
  document.body.appendChild(canvas)
}
<html>
  <body>
  </body>
</html>
Chris
  • 2,461
  • 1
  • 23
  • 29