美文网首页
canvas交互

canvas交互

作者: 洛洛kkkkkk | 来源:发表于2017-04-20 19:30 被阅读0次
    <!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>
    

    相关文章

      网友评论

          本文标题:canvas交互

          本文链接:https://www.haomeiwen.com/subject/pxalzttx.html