javascriptcanvasimagedata

Javascript Canvas get data from image and display it


I've no idea why this doesn't work. The src attribute of the image is changed with the new data, but the image is not actually visible. I tried with several different images. It's just javascript in a browser and Jquery is required.

<body>
<img src="" id="test">
</body>
<script>
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    let img = new Image();
    img.onload = getIt
    img.src = 'download.png';

    function getIt() {      
        canvas.width = this.width;
        canvas.height = this.height;
        const imageData = ctx.getImageData(0, 0, this.width, this.height);
        ctx.drawImage(this, canvas.width , canvas.height);
        ctx.putImageData(imageData, canvas.width, canvas.height);

        $('#test').get(0).src = canvas.toDataURL("image/png");
    }

</script>

I tried with several different images, all png. At the moment this is the entire code for the project so I don't foresee anything that could be interfering with it.

The result is this but the image cannot be seen:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAeCAYAAAAhDE4sAAAAMklEQVRIS+3SsQ0A....etc" id="test">

EDIT: It seems like it might be getting the data from the image incorrectly but I've no idea why...I mean why would it get the data but be incomplete or incorrect?


Solution

  • Please try this: (You don't need to get or put the image data)

    Also you were doing this:ctx.putImageData(imageData, canvas.width, canvas.height);. This means that you are drawing the image totally outside the canvas. Do this instead: ctx.putImageData(imageData, 0,0);

    const canvas = document.createElement("canvas");
    
        const ctx = canvas.getContext("2d");
        let img = new Image();
        img.onload = getIt
        img.src = "download.png";
    
        function getIt() {    
            canvas.width = this.width;
            canvas.height = this.height;
            //draw the image onto the canvas
            ctx.drawImage(this, 0,0);
            //use the data uri 
            test.src = canvas.toDataURL("image/png");
        }
    
    <img src="" id="test">