css 获取Javascript输出

aiazj4mn  于 2022-12-24  发布在  Java
关注(0)|答案(1)|浏览(116)

所以,我有一个简单的绘图应用程序,它基于javascript,运行在python flask上。我有一个javascript按钮,可以输出客户端绘制的截图到客户端。有人知道我如何用flask将图像输出回服务器吗?
代码:

    • 超文本标记语言:**
<canvas id="canvas"></canvas>
    • 联属萨摩亚**
const canvas = document.getElementById("canvas")
canvas.height = window.innerHeight
canvas.width = window.innerWidth

const ctx = canvas.getContext("2d")

let prevX = null
let prevY = null

ctx.lineWidth = 5

let draw = false

let clearBtn = document.querySelector(".clear")
clearBtn.addEventListener("click", () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
})

let saveBtn = document.querySelector(".save")
saveBtn.addEventListener("click", () => {
    let data = canvas.toDataURL("imag/png")
    let a = document.createElement("a")
    a.href = data
    a.download = "sketch.png"
    a.click()
})

window.addEventListener("mousedown", (e) => draw = true)
window.addEventListener("mouseup", (e) => draw = false)

window.addEventListener("mousemove", (e) => {
    if(prevX == null || prevY == null || !draw){
        prevX = e.clientX
        prevY = e.clientY
        return
    }

    let currentX = e.clientX
    let currentY = e.clientY

    ctx.beginPath()
    ctx.moveTo(prevX, prevY)
    ctx.lineTo(currentX, currentY)
    ctx.stroke()

    prevX = currentX
    prevY = currentY
})
    • 巨蟒**
from flask import Flask, render_template, request

app = Flask(__name__)
dirweb = "templates/"

app = Flask(__name__, template_folder=dirweb)
@app.route("/")
def hello_world():
    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=False)

希望有人知道

3mpgtkmj

3mpgtkmj1#

要使用Flask将图像数据从客户机发送到服务器,可以使用HTTP POST请求。
在JavaScript代码中修改saveBtn事件监听器,向服务器发送一个HTTP****POST请求,请求体为图片数据,可以使用fetch函数发送请求。

let saveBtn = document.querySelector(".save")
saveBtn.addEventListener("click", () => {
    let data = canvas.toDataURL("imag/png")
    // Send an HTTP POST request to the server with the image data as the request body
    fetch('/save', {
        method: 'POST',
        body: data
    })
    .then(response => {
        console.log(response)
    })
    .catch(error => {
        console.error(error)
    })
})

在Python代码中,添加一个新路由来处理POST请求,并将图像数据保存到服务器上的一个文件中。

from flask import Flask, render_template, request
import base64

app = Flask(__name__)
dirweb = "templates/"

app = Flask(__name__, template_folder=dirweb)

@app.route("/")
def hello_world():
    return render_template("index.html")

@app.route('/save', methods=['POST'])
def save_image():
    # Get the image data from the request body
    data = request.data

    # Decode the base64 encoded image data
    image_data = base64.b64decode(data)

    # Save the image data to a file
    with open("sketch.png", "wb") as f:
        f.write(image_data)

    return "Success"

if __name__ == "__main__":
    app.run(debug=False)

相关问题