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>
  • 相关阅读:
    Restful API
    Vue之指令
    Scrapy框架
    爬虫提高性能:串行、线程进程、异步非阻塞
    MongoDB
    Beautifulsoup模块
    请求库之selenium
    php 正则匹配中文
    Javascript的"预编译"思考
    PHP程序员面试技巧之口试题分享
  • 原文地址:https://www.cnblogs.com/xkxf/p/6754377.html
Copyright © 2011-2022 走看看