HTML / JS-在画布上绘制按钮

时间:2019-03-10 09:34:26

标签: javascript html python-2.7 flask

我对html知之甚少,对js知之甚少。因此,我想制作一个Flask网络应用程序以与我的Raspberry Pi进行交互。我需要相机的mjpg流,并且还希望能够与2个舵机(简单的命令;上,下,左,右)进行交互。因此,我复制了这个绘制图像的示例,并不断对其进行更新,对其进行了一些更改,感到高兴,然后我继续实施按钮。尝试了3-4种方法。他们没有出现。我觉得自己缺少一些基本知识,但是就像我说的那样,我对该主题知之甚少。 (我以为我可以从Flask做到)。这是代码:

python:

from flask import Flask, render_template
app = Flask(__name__)

LEFT, RIGHT, UP, DOWN, RESET = "left", "right", "up", "down", "reset"
AVAILABLE_COMMANDS = {
    'Left': LEFT,
    'Right': RIGHT,
    'Up': UP,
    'Down': DOWN,
    'Reset': RESET
}

@app.route("/")
def index():
    return render_template('index.html', commands=AVAILABLE_COMMANDS)

@app.route('/<cmd>')
def command(cmd=None):
    if cmd == RESET:
        camera_command = "X"
        response = "Resetting ..."
    else:
        camera_command = cmd[0].upper()
        response = "Moving {}".format(cmd.capitalize())

    return response, 200, {'Content-Type': 'text/plain'}


if __name__ == '__main__':
    app.debug = True
    app.run('0.0.0.0', 5000)
    app.run(debug = True)

html:

<html>
<head>
    <script type="text/JavaScript">
    var url = "static/01.jpg"; //url to load image from
    var refreshInterval = 500; //in ms
    var drawDate = null; //draw date string
    var img;

    function init() {
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");
        img = new Image();
        img.onload = function() {
            canvas.setAttribute("width", 640)
            canvas.setAttribute("height", 480)
            context.drawImage(this, 0, 0);
            if(drawDate) {
                var now = new Date();
                var text = now.toLocaleDateString() + " " + now.toLocaleTimeString();
                var maxWidth = 100;
                var x = img.width-10-maxWidth;
                var y = img.height-10;
                context.strokeStyle = 'black';
                context.lineWidth = 2;
                context.strokeText(text, x, y, maxWidth);
                context.fillStyle = 'white';
                context.fillText(text, x, y, maxWidth);
            };
       };
       refresh();
}
function refresh() {
    img.src = url + "?t=" + new Date().getTime();
    setTimeout("refresh()",refreshInterval);
}

</script>
<title>cam_ser</title>
</head>
<body onload="JavaScript:init();">
<canvas id="canvas"/>
<link rel="stylesheet" href="static/styles.css">
{# in index.html #}
{% for label, command in commands.items() %}
    <button class="command command-{{ command }}" value="{{ command }}">
        {{ label }}
    </button>
{% endfor %}

{# and then elsewhere #}
<script>
addEventListener("DOMContentLoaded", function() {
    var commandButtons = document.querySelectorAll(".command");
    for (var i=0, l=commandButtons.length; i<l; i++) {
        var button = commandButtons[i];
        button.addEventListener("click", function(e) {
            e.preventDefault();

            var clickedButton = e.target;
            var command = clickedButton.value;
            var request = new XMLHttpRequest();
            request.onload = function() {
                 alert(request.responseText);
            };
            request.open("GET", "/" + command, true);
            request.send();
        });
    }
}, true);
</script>

</body>

1 个答案:

答案 0 :(得分:0)

我不明白发生了什么。简单的答案是我需要修改以下行:

    def main_menu():          
    menu_choice = input("""
---------------------------------------
Welcome to the GCSE Celebrity Dogs Game
 Please choose an option from the menu
---------------------------------------
1) Play the game
2) Quit
""")
    if menu_choice == 1:
     deck_choice()
    elif menu_choice == 2:
     print("Exiting game.....")
     quit()
    else:
     main_menu()


correct_numbers = [6,8,10,12,14,16,18,20,22,24,26,28,30]


def deck_choice():
    num_cards = input("""
How many cards owuld you liek to play with?
**Please note this must be a number between 4 and 30 and cannot be odd**
""")
    if num_cards not in correct_numbers:
        print("Sorry, that number isnt valid. Please enter another number")
    else:
        return num_cards


main_menu() 

就是这样。它与js脚本无关。我不知道为什么我要这么做。

编辑:

它与js脚本无关,但要使图像正确显示,您必须将js中的画布大小与以下项匹配:

<canvas id="canvas" width="640" height="480"/>