Как динамически фиксить линии с нечетной шириной?

Если тут прибавление/отнимание 0.5px работает

context1 = c1.getContext('2d')
context2 = c2.getContext('2d')

width = c1.width = c2.width = 160
height = c1.height = c2.height = 160

line(context1, width/2)
line(context2, width/2 + 0.5)

function line(context, x) {
  context.beginPath()
  context.moveTo(x, 0)
  context.lineTo(x, height)
  context.stroke()
}
body {
  margin: 0;
  height: 100vh;
}

canvas {
  display: inline-block;
  background: tomato;
}

canvas#c2 {
  background: lightgreen;
}
<canvas id=c1></canvas><canvas id=c2></canvas>

то что делать здесь, когда заранее размеры canvas не известны и могут измениться в любой момент?

context = canvas.getContext('2d')
resize()
update()
onresize = resize

function resize() {
  width = canvas.width = innerWidth
  height = canvas.height = innerHeight
}

function update() {
  context.beginPath()
  context.moveTo(width/2, 0)
  context.lineTo(width/2, height)
  context.stroke()
  
  requestAnimationFrame(update)
}
body {
  margin: 0;
}

canvas {
  display: block;
}
<canvas id=canvas></canvas>

или вот, например, как мне знать, когда нужно прибавлять эти 0.5px, чтобы линия и черточки на ней выглядели правильно при любом разрешении?

context = canvas.getContext('2d')
onresize = resize
resize()

function resize() {
  width = canvas.width = innerWidth
  height = canvas.height = innerHeight
  cx = width / 2
  cy = height / 2
}

function coordinateSystem(gap) {
  context.lineWidth = 0.5

  drawLine(0, cy, width, cy)

  context.lineWidth = 1

  for (let i = 1; i < width / 2 / gap; i++) {
    let x = cx - i * gap
    hdash(x, cy)
    x = cx + i * gap
    hdash(x, cy)
  }
}

function drawLine(x1, y1, x2, y2) {
  context.beginPath()
  context.moveTo(x1, y1)
  context.lineTo(x2, y2)
  context.stroke()
}

function hdash(x, y) {
  drawLine(x, y - 7, x, y + 7)
}

function update() {
  context.clearRect(0, 0, width, height)
  coordinateSystem(20)
  requestAnimationFrame(update)
}

update()
body {
  margin: 0;
}

canvas {
  display: block;
}
<canvas id="canvas"></canvas>

Я читал ответы здесь, но мне если честно ничего не помогло.


Ответы (1 шт):

Автор решения: Stranger in the Q

Предлагаю такой способ:

Math.floor(x) + 0.5

let context = c1.getContext('2d');

redraw(250);

function redraw(v) {
  c1.width = v;
  line(Math.floor(c1.width/3) + 0.5)
  line(Math.floor(c1.width/2) + 0.5)
}

function line(x){
  context.beginPath()
  context.moveTo(x, 0)
  context.lineTo(x, c1.height)
  context.stroke()
}
canvas {
  background: tomato;
}
<input type="range" oninput="redraw(this.value)" min=200 max=300>
<br>
<canvas id=c1></canvas>

→ Ссылка