canvas交互

2017-04-20  本文已影响0人  洛洛kkkkkk
<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #kk {
                box-shadow: 0 0 10px 0 sandybrown;
            }
        </style>
    </head>

    <body>
        <canvas id="kk" width="600" height="600"></canvas>
    </body>
    <script type="text/javascript">
        var myCanvas = document.getElementById("kk");
        var context = myCanvas.getContext("2d");
        var isDown = false;

        function Rect(x, y, w, h, color) {
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
            this.color = color;
        }
        Rect.prototype.draw = function() {
            context.fillStyle = this.color;
            context.fillRect(this.x, this.y, this.w, this.h);
        }
        var one = new Rect(100, 100, 50, 50, "blue");
        var two = new Rect(300, 300, 50, 50, "red");
        one.draw();
        two.draw();

        myCanvas.onmousedown = function(e) {
            var x = e.offsetX;
            var y = e.offsetY;
            if(x > one.x && x < one.x + one.w && y > one.y && y < one.y + one.h) {
                isDown = true;
            }
        }
        document.onmouseup = function() {
            isDown = false;
        }
        
        myCanvas.onmousemove = function(ev) {
            if(!isDown) {
                return;
            }
            var x = ev.offsetX;
            var y = ev.offsetY;
            one.x = x - one.w / 2;
            one.y = y - one.h / 2;

            context.clearRect(0, 0, myCanvas.width, myCanvas.height);

            one.draw();
            two.draw();
            if(one.x + one.w > two.x && one.x < two.x + two.w && one.y + one.h > two.y && one.y < two.y + two.h) {
                console.log("hha");
            }

        }
    </script>

</html>
上一篇下一篇

猜你喜欢

热点阅读