When drawing a rectangle on canvas and getting its color with getImageData the color is exactly what it's defined (with fillRect). On the other hand, when drawing a line on canvas and getting its color with getImageData, the color sometimes the same and sometimes is different from what it was defined (with strokeStyle)?
Feb 16 2021 UPDATE: From answers and given links, a solution for horizontal and vertical lines is found and pretty simple, just shift the drawn pixels (line coordinates: for horizontal – y coord, for vertical x coord) to a certain amount of pixels which depends on lineWidth (lineWidth is even – no shift, lineWidth is odd – 0.5px shift).
The questions are:
why the color of line differs from what it was defined with strokeStyle? (the question is answered and can be derived from links to related questions)
is there a way to draw a line of one defined color and of defined width? (solution for horizontal and vertical lines is found – described above)
is there a way to draw a diagonal line of one defined color and of defined lineWidth?
const canvas = document.createElement('canvas')
document.body.appendChild(canvas)
const ctx = canvas.getContext('2d')
ctx.strokeStyle = 'rgba(3,0,0,255)'
ctx.fillStyle = 'rgba(3,0,0,255)'
ctx.lineWidth = 1
ctx.beginPath()
ctx.moveTo(10, 10) // solution to get sharp line: ctx.moveTo(10, 10.5)
ctx.lineTo(20, 10) // // solution to get sharp line: ctx.moveTo(20, 10.5)
ctx.stroke()
// diagonal -45 deg
ctx.beginPath()
ctx.moveTo(10, 20)
ctx.lineTo(20, 30)
ctx.stroke()
ctx.fillRect(10,15,1,1)
console.log('--line horizontal');
console.log(ctx.getImageData(10, 8, 1, 1).data)
console.log(ctx.getImageData(10, 9, 1, 1).data) // expected to return [0, 0, 0, 0] --> returns [2, 0, 0, 127] (explained, solution described above)
console.log(ctx.getImageData(10, 10, 1, 1).data) // expected to return [3, 0, 0, 255] --> returns [2, 0, 0, 127] (explained, solution described above)
console.log(ctx.getImageData(10, 11, 1, 1).data)
console.log('--line diagonal');
console.log(ctx.getImageData(10, 18, 1, 1).data)
console.log(ctx.getImageData(10, 19, 1, 1).data) // ?! expected to return [0, 0, 0, 0] --> returns [3, 0, 0, 74]
console.log(ctx.getImageData(10, 20, 1, 1).data) // ?! expected to return [3, 0, 0, 255] --> returns [3, 0, 0, 254]
console.log(ctx.getImageData(10, 21, 1, 1).data) // ?! expected to return [0, 0, 0, 0] --> returns [3, 0, 0, 75]
console.log(ctx.getImageData(10, 22, 1, 1).data)
console.log('--rect');
console.log(ctx.getImageData(9, 14, 1, 1).data)
console.log(ctx.getImageData(10, 14, 1, 1).data)
console.log(ctx.getImageData(11, 14, 1, 1).data)
console.log(ctx.getImageData(9, 15, 1, 1).data)
console.log(ctx.getImageData(10, 15, 1, 1).data)
console.log(ctx.getImageData(11, 15, 1, 1).data)
console.log(ctx.getImageData(9, 16, 1, 1).data)
console.log(ctx.getImageData(10, 16, 1, 1).data)
console.log(ctx.getImageData(11, 16, 1, 1).data)