我有一个圆和一个随机点。目前,这个随机点实际上是随机的,但我希望它位于背景网格中一个分区的中心。
我用当前的随机点制作了一个片段:
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
const size = 512
canvas.width = size
canvas.height = size
// Draw grid
ctx.beginPath()
ctx.strokeStyle = '#000'
const gridDivisions = 10
const gridSize = size / gridDivisions
for (let i = 0; i <= gridDivisions; i++) {
ctx.moveTo(0, i * gridSize)
ctx.lineTo(size, i * gridSize)
ctx.moveTo(i * gridSize, 0)
ctx.lineTo(i * gridSize, size)
}
ctx.stroke()
ctx.closePath()
// Draw circle
const radius = 180
ctx.beginPath()
ctx.strokeStyle = '#F00'
ctx.arc(size / 2, size / 2, radius, 0, Math.PI * 2)
ctx.stroke()
ctx.closePath()
// Draw random point
const angle = Math.random() * Math.PI * 2
ctx.save()
ctx.beginPath()
ctx.strokeStyle = '#000'
ctx.translate(Math.cos(angle) * radius + size / 2, Math.sin(angle) * radius + size / 2)
ctx.moveTo(-5, 5)
ctx.lineTo(5, -5)
ctx.moveTo(5, 5)
ctx.lineTo(-5, -5)
ctx.stroke()
ctx.closePath()
ctx.restore()
// Draw center
ctx.save()
ctx.beginPath()
ctx.strokeStyle = '#00F'
ctx.translate(size / 2, size / 2)
ctx.moveTo(-5, 5)
ctx.lineTo(5, -5)
ctx.moveTo(5, 5)
ctx.lineTo(-5, -5)
ctx.stroke()
ctx.closePath()
ctx.restore()
<canvas id="canvas"></canvas>
并且我希望黑叉位于随机网格分区的中心,就像这样(在与圆碰撞的任何分区中):
答案 0 :(得分:2)
您只需要将点的坐标按比例缩小到像元大小,然后取它们的整数值,按比例缩小,然后加一半像元大小。
更易于显示,请参见下面的代码段
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
const size = 512
canvas.width = size
canvas.height = size
// Draw grid
ctx.beginPath()
ctx.strokeStyle = '#000'
const gridDivisions = 10
const gridSize = size / gridDivisions
for (let i = 0; i <= gridDivisions; i++) {
ctx.moveTo(0, i * gridSize)
ctx.lineTo(size, i * gridSize)
ctx.moveTo(i * gridSize, 0)
ctx.lineTo(i * gridSize, size)
}
ctx.stroke()
ctx.closePath()
// Draw circle
const radius = 180
ctx.beginPath()
ctx.strokeStyle = '#F00'
ctx.arc(size / 2, size / 2, radius, 0, Math.PI * 2)
ctx.stroke()
ctx.closePath()
// Draw random point
const angle = Math.random() * Math.PI * 2
let tx = Math.cos(angle) * radius + size / 2;
let ty = Math.sin(angle) * radius + size / 2;
[tx, ty] = [tx, ty].map(c => (c / gridSize | 0) * gridSize + gridSize / 2);
ctx.save()
ctx.beginPath()
ctx.strokeStyle = '#000'
ctx.translate(tx, ty)
ctx.moveTo(-5, 5)
ctx.lineTo(5, -5)
ctx.moveTo(5, 5)
ctx.lineTo(-5, -5)
ctx.stroke()
ctx.closePath()
ctx.restore()
// Draw center
ctx.save()
ctx.beginPath()
ctx.strokeStyle = '#00F'
ctx.translate(size / 2, size / 2)
ctx.moveTo(-5, 5)
ctx.lineTo(5, -5)
ctx.moveTo(5, 5)
ctx.lineTo(-5, -5)
ctx.stroke()
ctx.closePath()
ctx.restore()
<canvas id="canvas"></canvas>