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

标签 javascript canvas html5-canvas sine-wave

我不知道水平调整正弦波大小以及调整窗口大小时比例缩小的正确方法。它仍然需要在垂直方向上处于同一位置,我现在需要的只是水平和比例调整大小。正弦波如以下 js-fiddle 所示: 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()

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

最佳答案

不知道是不是你想要的

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

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
}

关于javascript - 水平和按比例调整正弦波大小 - js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59006921/

相关文章:

javascript - 为什么我的 strokeStyle 是透明的?

python - 我无法在 Tkinter python 中将图像加载到 Canvas 上

javascript - 每次我再次运行时,动画变得越来越快

javascript - 使用点击点在 Canvas 中拉直脸部图像

javascript - Angular 搜索框

JavaScript 去除所有的 css 样式信息

javascript - Foundation 5 slider 显示两位小数

android - 如何从绘制到位图中的文本中删除伪影

javascript - 如何将 html5 canvas 绘图下载为图像

javascript - 时刻js UTC+00 :00 giving 1 hr extra