最近在项目中需要操作canvas绘制圆内网格图并点击高亮,因此将实现demo记录下来
首先看填充效果如下
实现步骤
- 第一步:绘制外圆
-
// 绘制外层圆 function drawCicle() { ctx.beginPath() ctx.strokeStyle = '#191919' ctx.arc(0, 0, canvas.width / 2 - pendding, 0, 2 * Math.PI) ctx.closePath() ctx.stroke() }
- 第二步:绘制网格
-
// 获取左上角点 function getRect() { const result = [] const xC = canvas.width / 2 const yC = canvas.height / 2 const minX = -xC const maxX = xC const minY = -yC const maxY = yC for (let i = minX; i < maxX; i+= 20) { // console.count('times') for (let j = minY; j < maxY; j+=20) { const point = [i, j] if (isInCicle(xC, point) && isInCicle(xC, [i + 20, j]) && isInCicle(xC, [i + 20, j + 20]) && isInCicle(xC, [i, j + 20])) { result.push(point) } } } // console.log('result', result, minX, minY, maxX, maxY) return result }