javascriptcanvashtml5-canvassine-wave

Resize sine wave horizontally and proportionally - js


I don't know the correct way to resize the sine wave horizontally and have the proportions scale down when you resize the window. It still needs to be at the same place vertically, it's only horizontal and proportional resizing i need now. The sine wave is shown in this js-fiddle: https://jsfiddle.net/x2audoqk/7/

js-code for the sine wave:

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()

How do i achieve this? If you need some more information or clarification be free to ask.


Solution

  • I don't know if it's what you want,

    but by adding this line, the length of the wave fits the width of the 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/

    edit

    to make it clean, one should also change the following so that the length of the wave is the same calculation before resizing

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