change canvas image with javascript

2019-07-28 05:31发布

问题:

the desired behavior is when the document loads, canvas draws image 0. when the invisible div is clicked, canvas draws image 1, on mouseup or mouseout, it reverts back to image 0.

I left the css out because I got that working...just need to know what I'm doing wrong with the javascript function. right now it doesn't display anything, not even the first image.

<!DOCTYPE HTML>
<html>
    <head>
        <script type="text/javascript">
        function imgChange(imagePath)
            var c=document.getElementById("myCanvas");
            var ctx=c.getContext("2d");
            var img=new Image();
            img.onload = function(){
            ctx.drawImage(img,0,0);
            };
            img.src=imagePath; <!-- I THINK THIS IS WRONG?
        </script>
    </head>

    <body>

            <canvas id="myCanvas" width="506" height="319"
onload="imgChange('0.gif')" style="border:1px solid #c3c3c3;">
            Your browser does not support the canvas element.
            </canvas>



            <div id="button1" onMouseDown="imgChange('1.gif')" onMouseUp="imgChange('0.gif')" onMouseOut="imgChange('0.gif')"></div>
            <div id="key2"></div>




    </body>

</html>

回答1:

your code is missing an ending block

function imgChange(imagePath) {
            var c=document.getElementById("myCanvas");
            var ctx=c.getContext("2d");
            var img=new Image();
            img.onload = function(){
                  ctx.drawImage(img,0,0);
            };
            img.src=imagePath;
}

The last '}' is missing



回答2:

JavaScript looks good. But you can't click on an invisible div. Make the div visible and try.

Be aware of same origin policy too. Image path should be in your domain. If you are running in localhost you might need to have a local HTTP server.