简体   繁体   中英

HTML5 canvas toDataURL not working with an image on the canvas

What i want to do is to draw an image that I have saved locally onto a canvas. I then want to convert that canvas to a png image. The image loads on the canvas but the png image that I create is blank. Does anyone know how to fix this?

 <!DOCTYPE html> <html> <head> </head> <body> <img src="" id="canvasImage" /> <canvas id="canvasId" width="160" height="145"></canvas> <script> var canvas = document.getElementById('canvasId'); var context = canvas.getContext("2d"); image = new Image(); image.src = "images/rightarrow.png"; image.onload = function(){ context.drawImage(image, 0, 0); } var imgTag = canvas.toDataURL("image/png"); document.getElementById("canvasImage").src = imgTag; </script> </body> </html> 

You need to create your image inside onload handler

        image = new Image();
        image.src = "images/rightarrow.png";
        image.onload = function(){
            context.drawImage(image, 0, 0);
            var imgTag = canvas.toDataURL("image/png");
            document.getElementById("canvasImage").src = imgTag;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM