如果加/减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>
我在这里阅读了答案,但说实话,没有任何帮助。
我建议这样:
Math.floor(x) + 0.5