console
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = 200
const speed = 0.05
const range = 30
let angle = 0
let xpos = 0
let sinYpos = canvas.height / 2
let cosYpos = canvas.height / 2
function drawFrame() {
requestAnimationFrame(drawFrame)
const startX = xpos
const startSinYpos = canvas.height / 2 + Math.sin(angle) * range
const startCosYpos = canvas.height / 2 + Math.cos(angle) * range
xpos += speed * 20
angle += speed
// Math.sin 运动轨迹
ctx.beginPath()
ctx.strokeStyle = 'black'
// Math.sin(angle) 的值从0增长到1再下降到-1
sinYpos = canvas.height / 2 + Math.sin(angle) * range
ctx.moveTo(startX, startSinYpos)
ctx.lineTo(xpos, sinYpos)
ctx.stroke()
// Math.cos 运动轨迹
ctx.beginPath()
ctx.strokeStyle = 'red'
// Math.cos(angle) 的值从1下降到-1再到0
cosYpos = canvas.height / 2 + Math.cos(angle) * range
ctx.moveTo(startX, startCosYpos)
ctx.lineTo(xpos, cosYpos)
ctx.stroke()
}
drawFrame()
<canvas id="canvas"></canvas>
<div>
<p style="color:black">Math.sin <em>0 ~ 1 ~ -1</em></p>
<p style="color:red">Math.cos <em>1 ~ -1 ~ 0</em></p/>
</div>
html, body {
width: 100%;
height: 100%;
overflow: hidden;
}