How to remove canvas image on a onmouseout?

好久不见. 提交于 2019-12-25 02:01:33

问题


I am trying to change the image in canvas ID 'A' with mouseout on canvas ID 'e' I have been able to get the mousover to work and add a image to canvas 'A', but not remove it.

    <script>
            function init() {
                setImageOne();
            }

            function setImageOne() { setImage('images/paul01.jpg'); }

            <!--function setImageTwo() { setImage('images/paul02.jpg'); }-->

            function unsetImageOne() { largeImage('images/full/cartoonPaul02.jpg'); }

            function setImageTwo() { largeImage('images/full/cartoonPaul01.jpg'); }

            function setImage(src) {
                var canvas = document.getElementById("l");
                var context = canvas.getContext("2d");
                if (context == null) return;
                var img = new Image();
                img.src = src;
                context.drawImage(img, 0, 0, 166, 276);
            }

            function largeImage(src){
                var canvas = document.getElementById("A");
                var context = canvas.getContext("2d");
                if (context == null) return;
                var img = new Image();
                img.src = src;
                context.drawImage(img, 0, 0, 300, 400);
            }
    </script>
        <div id="container">
            <header>
            <a href='../../'><h3>Everything else</h3></a>

</header>
        <div id="main" role="main">
        <body onload="init()">

            <div class="canvas">
                <canvas id="l" width="166" height="276" onmouseover="setImageTwo()" onmouseout="unsetImageOne()"></canvas>
            </div>

            <div class="canvas">
                <canvas id="A" width="300" height="400"></canvas>
            </div>

回答1:


Removing something from a canvas is impossible in such that when you draw something, only pixels are saved. There is therefore no concept of an image anymore after drawing.

What you can do, however, is clearing the full canvas before drawing another image. This code might be appropriate for largeImage. The same goes for smallImage. I also advise you to use image.onload to make sure the image is only drawn when it is fully loaded.

function largeImage(src){
    var canvas = document.getElementById("A");
    var context = canvas.getContext("2d");
    var canvas2 = document.getElementById("l");
    var context2 = canvas.getContext("2d");
    if (context == null) return;
    var img = new Image();
    img.src = src;
    context2.clearRect(0, 0, 166, 276);
    img.onload = function() {
        context.drawImage(img, 0, 0, 300, 400);
    }
}


来源:https://stackoverflow.com/questions/7110555/how-to-remove-canvas-image-on-a-onmouseout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!