I need to display and take image sizes when loading

40 Views Asked by At

Everything works except the image size. I have been working on this for a long time and I cannot understand what is wrong I want to know the size in other ways, it comes back to me undefined and this code does not execute "if {}" JavaScript :

const selectInput = document.querySelector("#select-input")
const imageFieldChoice = document.querySelector("#image-field-choice")

selectInput.addEventListener("change", function informFile(input) {
    const imgsArray = [...this.files]
    let i = 0
    imgsArray.forEach(img => {
        const imgBlock = document.createElement("div")
        imgBlock.classList.add("img-block")

        const canvas = document.createElement("canvas")
        const context = canvas.getContext("2d")
        canvas.classList.add("img-load-block")
        canvas.id = "imgCanvas"

        const imgElement = document.createElement("img")
        imgElement.classList.add("img-load")
        imgElement.id = "img-load"
            const reader = new FileReader()

            reader.readAsDataURL(imgsArray[i])
            reader.addEventListener("load", (img) => {
                imgElement.src = img.target.result

                //main part
                if (img.naturalWidth) {
                    var width = img.naturalWidth
                    var height = img.naturalHeight
                    console.log(width)
                    console.log(height)
                } else {
                    console.log("!")
                }
                //main part\

                context.drawImage(imgElement, 0, 0, width, height)
            })
            i++

        const imgName = document.createElement("h3")
        imgName.classList.add("img-name")
        imgName.textContent = img.name

        imageFieldChoice.appendChild(imgBlock)
        imgBlock.appendChild(canvas)
        canvas.appendChild(imgElement)
        imgBlock.appendChild(imgName)
    })
})
0

There are 0 best solutions below