canvas 生成旋转的进度刻线
2024-01-11 本文已影响0人
litielongxx

支持控制y轴的俯仰角度,视觉行调整。多为环形旋转的效果;
来自gpt
结构
<canvas id="map1_border"></canvas>
const canvas = document.getElementById('map1_border')
const ctx = canvas.getContext('2d')
const centerX = canvas.width / 2
const centerY = canvas.height / 2
const radiusX = 100
const radiusY = 50
const numTicks = 36 // 刻度线数量
const tickLength = 10 // 刻度线长度
const rotationSpeed = 0.5 // 旋转速度,单位:度/帧
let angle = 0
// 控制形变程度的参数
const scaleX = 1 // 沿 x 轴的缩放比例
const scaleY = 0.7 // 沿 y 轴的缩放比例
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
// 绘制倾斜的刻度线
for (let i = 0; i < numTicks; i++) {
const tickAngle = (i / numTicks) * 2 * Math.PI + angle * (Math.PI / 180)
const x1 = centerX + (radiusX - tickLength) * Math.cos(tickAngle)
const y1 = centerY + (radiusY - tickLength) * Math.sin(tickAngle)
const x2 = centerX + radiusX * Math.cos(tickAngle)
const y2 = centerY + radiusY * Math.sin(tickAngle)
ctx.save() // 保存当前绘图状态
ctx.translate(centerX, centerY) // 将坐标原点移动到画布中心
ctx.scale(scaleX, scaleY) // 沿 x 和 y 轴进行缩放,控制形变程度
ctx.beginPath()
ctx.moveTo(x1 - centerX, y1 - centerY) // 将坐标原点移动到刻度线的起点
ctx.lineTo(x2 - centerX, y2 - centerY) // 绘制形变后的刻度线
ctx.strokeStyle = '#ccc'
ctx.lineWidth = 2
ctx.stroke()
ctx.restore() // 恢复之前保存的绘图状态
}
// 更新角度
angle = (angle + rotationSpeed) % 360
requestAnimationFrame(draw)
}
draw()