我有一个 .ejs 文件,并添加了一个画布。当我点击名为circle的html画布元素时,如何将值发送到nodejs?是否应该有一个与 fetch 一起使用的 POST 方法?
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<canvas id ="canvas" style="border: solid 5px blue";></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 1000;
canvas.height = 800;
var circle = new Path2D();
circle.arc(250, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "gray";
circle.closePath
ctx.fill(circle);
canvas.addEventListener('click', (event) => {
var circle_1 = ctx.isPointInPath(circle, event.offsetX, event.offsetY)
if (circle_1) {
//I want to send values from here
}
})
</script>
</body>
</html>
从 html 到后端交换数据的唯一方法是使用这 02 个方法中的一个
由于您的事件不是从通用表单引发的,因此您需要ajax。所以在你的“onclick”事件中放这样的东西:
无需外部库
var xmlhttp = new XMLHttpRequest();
var theUrl = "/some/express/souter";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({"foo": "bar"}));
//source: https://stackoverflow.com/a/39519299/3957754
您还有另一种使用 ajax 的选择: