zoukankan      html  css  js  c++  java
  • 【JavaScript】键盘控制小球

    参考:

    1、Simple Canvas Game

    2、javaScript 事件监听

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>moveBall</title>
        </head>
        <body>
            <script>
    //            a test
    //            addEventListener("keydown", function (e) {
    //                console.log(e);
    //            }, false);
                var screenWidth = document.documentElement.clientWidth;
                var screenHeight = document.documentElement.clientHeight;
                
                var ball = document.createElement("div");
                
                ball.style.width = 124 + "px";
                ball.style.height = 124 + "px";
                
                ball.style.backgroundColor = "coral";
                ball.style.borderRadius = "50%";
                
                var X = Math.random()*screenWidth;
                var Y = Math.random()*screenHeight;
                ball.style.position = "absolute";
                ball.style.left = X + "px";
                ball.style.top = Y + "px";
                
                document.body.appendChild(ball);
                
                function repaint() {
                    ball.style.left = X + "px";
                    ball.style.top = Y + "px";
                }
                
                function moveUp() {
                    Y--;
                    repaint();
                }
                
                function moveDown() {
                    Y++;
                    repaint();
                }
                
                function moveLeft() {
                    X--;
                    repaint();
                }
                
                function moveRight() {
                    X++;
                    repaint();
                }
                
                addEventListener("keydown", function (e) {
                    if (e.key == "ArrowUp") {
                        moveUp();
                    }
                    if (e.key == "ArrowDown") {
                        moveDown();
                    }
                    if (e.key == "ArrowLeft") {
                        moveLeft();
                    }
                    if (e.key == "ArrowRight") {
                        moveRight();
                    }
                }, false);
            </script>
        </body>
    </html>
  • 相关阅读:
    自定义Response
    并发编程之进程
    并发编程知识储备
    正则表达式和re模块
    Scrapy框架
    http协议和Chrome抓包工具
    requests库
    Beautifulsoup
    xpath
    Mysql一些操作
  • 原文地址:https://www.cnblogs.com/xkxf/p/6754377.html
Copyright © 2011-2022 走看看