水平和按比例调整正弦波大小-JS

时间:2019-11-23 11:03:26

标签: javascript canvas html5-canvas sine-wave

我不知道正确调整水平正弦波大小以及在调整窗口大小时缩小比例的正确方法。它仍然需要垂直放置在同一位置,现在只需要水平和比例调整大小即可。正弦波显示在此js小提琴中: https://jsfiddle.net/x2audoqk/7/

正弦波的js代码:

const canvas = document.querySelector("canvas")
const c = canvas.getContext("2d")

canvas.width = innerWidth
canvas.height = innerHeight

// Resize wave vertically
window.addEventListener("resize", () => {
    canvas.width = innerWidth
    canvas.height = innerHeight
    wave.y = canvas.height / 1.5
})

const wave = {
    y: canvas.height / 1.5,
    length: -0.0045,
    amplitude: 47.5,
    frequency: 0.0045
}

let increment = wave.frequency

const animate = () => {
    requestAnimationFrame(animate)

    // Deletes previous waves
    c.clearRect(0, 0, canvas.width, canvas.height)

    c.beginPath()

    // Get all the points on the line so you can modify it with sin
    for (let i = 0; i <= canvas.width; i++) {
        c.moveTo(i, wave.y + Math.sin(i * wave.length + increment) * wave.amplitude * Math.sin(increment))
        c.lineTo(i, canvas.height)
    }

    // Style
    c.strokeStyle = 'rgba(1, 88, 206, .25)'
    c.stroke()
    increment += wave.frequency
    c.closePath()
}
animate()

我该如何实现?如果您需要更多信息或澄清,请随时询问。

1 个答案:

答案 0 :(得分:1)

我不知道这是否是你想要的

但是通过添加这条线,波浪的长度适合画布的宽度

window.addEventListener("resize", function () {
    canvas.width = innerWidth
    canvas.height = innerHeight
    wave.y = canvas.height / 1.5
    wave.length = -2/canvas.width // <---- add this line
})

https://jsfiddle.net/gui3_/mwzun5dr/1/

编辑

为使其整洁,还应更改以下内容,以便在调整大小之前波的长度是相同的计算


const wave = {
    y: canvas.height / 1.5,
    length: -2/canvas.width, //-0.0045,
    amplitude: 47.5,
    frequency: 0.0045
}