0

I have an .ejs file and I added a canvas. How do I do send values to nodejs when I click on the html canvas element named circle? Is there supposed to be a POST method used with fetch?

<!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>
Stefan
  • 17
  • 4

1 Answers1

0

The only way to exchange data from html to backend is using on of these 02 methods

Since your event is not raised from a common form, you need ajax. So in your "onclick" event put something like this:

Without external library

var xmlhttp = new XMLHttpRequest();
var theUrl = "/some/express/router";
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

You have another options to use ajax:

Backend

In the previous example, /some/express/router refers to some route in your backend.

Before of use ajax, you need to develop a backend http endpoint to receive data and store it in your favorite database. Check :

JRichardsz
  • 14,356
  • 6
  • 59
  • 94