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>
1
  • Do you have the insert to database with nodejs solved? Commented Aug 18, 2023 at 1:44

1 Answer 1

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 :

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.