Instructions for creating a circle with a click using JavaScript

Although I primarily work with Python and not JavaScript, I find myself in need of drawing circles on a web page at the location where a user clicks. Since I rely on Selenium for this task, it's essential for me to precisely pinpoint the click location. However, clicking based on coordinates sometimes leads to incorrect actions, which is why I am looking for a way to control and highlight these clicks.

Despite my attempts using the code snippet below (which unfortunately didn't yield the desired results), I stumbled upon a similar solution. Regrettably, neither approach has provided me with the working solution needed to effectively highlight the clicked areas.

var canv = document.createElement('canvas');
canv.id = 'canvas';

document.body.appendChild(canv);
document.getElementById('canvas').appendChild(canv);
onclick = function showCoords(event) {
  var x = event.clientX;
  var y = event.clientY;
  var radius = 5;
  var canvas = document.getElementsByTagName('canvas');
  var ctx = canvas.getContext('2d');
  ctx.beginPath();
  ctx.arc(x, y, radius, 40, 0, 2 * Math.PI);
  ctx.stroke();
  var coords = 'X coords: ' + x + ', Y coords: ' + y;
  console.log(coords);
}

Answer №1

Attempting to add the canvas onto itself

This actually functions as intended

var newCanvas = document.createElement('canvas');
newCanvas.id = 'myCanvas';
document.body.appendChild(newCanvas);
var context = newCanvas.getContext('2d');
newCanvas.addEventListener("click",function(event) {
  var xCoord = event.clientX;
  var yCoord = event.clientY;
  var circleRadius = 5;
  context.beginPath();
  context.arc(xCoord, yCoord, circleRadius, 40, 0, 2 * Math.PI);
  context.stroke();
  var coordinates = 'X coords: ' + xCoord + ', Y coords: ' + yCoord;
  console.log(coordinates);
})

Answer №2

The choice has been made

var newCanvas = document.createElement('canvas');
document.body.appendChild(newCanvas);
newCanvas.id = 'canvas';
newCanvas.style.position = 'absolute';
newCanvas.style.left = "0px";
newCanvas.style.top = "0px";
newCanvas.width = window.innerWidth;
newCanvas.height = window.innerHeight;

var context = newCanvas.getContext('2d');
newCanvas.addEventListener("click", function (event) {
  var xCord = event.clientX;
  var yCord = event.clientY;
  context.fillStyle = "#2980b9";
  context.beginPath();
  context.arc(xCord, yCord, 10, 0, 2 * Math.PI);
  context.fill();
  context.closePath();
  setTimeout(function () { context.clearRect(0, 0, newCanvas.width, newCanvas.height) }, 300);
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Iframes are not compatible with JQuery UI dialogs

After attempting to open a URL within an Iframe in a JQuery dialog box, I encountered the following issue: Here is the code snippet that I used: http://pastebin.com/Wqf0mGhZ I am looking for a solution to make sure that the dialog displays all of the con ...

Adjust the width of the table border without affecting the positioning of any other elements

I designed a table with buttons that, when clicked, increase their border width from 1px to 3px. Despite browsing through resources like Javascript - Changing border-width without moving surrounding elements., Don't affect positioning of other element ...

The issue arises when using an Angular directive with an input type set as "number"

When the input type is text, the code below works perfectly fine. However, it fails to function when the input type is changed to number. <div ng-app="myApp" ng-controller="myCtrl as model"> <input type="text" ng-model="cero" ng-decimal > ...

Error: Unable to locate specified column in Angular Material table

I don't understand why I am encountering this error in my code: ERROR Error: Could not find column with id "continent". I thought I had added the display column part correctly, so I'm unsure why this error is happening. <div class="exa ...

Extracting attribute names from a model's schema in Dynamoose v3: A guide

Exploring dynamoosev2: T extends Document; model: ModelType<T>; const attributes: string[] = model.schemas[0].attributes(); Is there a different approach to retrieve attribute names from the model in dynamoose v3? Transitioning to dynamoose v3: T ...

Modify the color of the header on Material-UI Date Picker

I recently integrated a Material-UI Date Picker into my React Single Page Application and now I'm facing an issue with changing the header color. I attempted to modify it using the muiTheme palette property, but unfortunately, the header color remains ...

Convert an array of string values into a JSON format

I need help with converting an array stored in my database to a more user-friendly format. Currently, it is saved as follows: ["size:medium","height:10cm"] This format makes it difficult to display in a table. I am wondering if there is a way to conver ...

JavaScript - Replacing key/value pairs in an object and transferring them to a different object

I am struggling with accessing and modifying the keys, values, and entries in an object (array), then transferring it to a new empty object (newArray). While I can retrieve the keys, values & entries, I'm facing difficulty making changes to them. The ...

What is the most effective web page element tag to use for locating and extracting values using Webdrive?

For my UI testing using Selenium in C#, I need to figure out the best way to "mark" my web elements for future ease of testing and maintenance. Whether it's an <input>, <div>, or any other element, what should I use? Is it better to use id ...

In Chrome, the `Jquery $('input[name=""]').change(function will not be triggered unless there is an unhandled error following it

Here is a script that I've created to make certain inputs dependent on the selection of a radio button. The 'parent' input in this case is determined by the radio button choice. Upon document load, the script initially hides parent divs of ...

Invoke the javascript function by referencing the JavaScript file

I'm encountering an issue with two JavaScript files. One file uses the prototype syntax, while the other utilizes jQuery. Unfortunately, they don't seem to work harmoniously together. I've attempted calling the functions within the files usi ...

Switch between light and dark mode on a webpage using HTML

I am looking to create a script using JavaScript, HTML, and CSS that can toggle between dark mode and night mode. Unfortunately, I am unsure of how to proceed with this task. https://i.sstatic.net/xA3Gq.png https://i.sstatic.net/v5vq5.png My goal is to ...

How can I retrieve URL parameters prior to sending them to the server?

Can all the parameters from a URL be extracted? For instance, in https://e-consultaruc.sunat.gob.pe/cl-ti-itmrconsruc/frameCriterioBusqueda.jsp Is it feasible to collect all the parameters present in the URL when submitting the required information and cl ...

Converting a data-attribute list into an array

My current setup includes an image with the following properties: <img id="img" data-list="['image2.jpg', 'image3.jpg', 'image4.jpg']" src="image1.jpg"> I am wondering how I can extract the list of images from the data ...

Utilizing pop-up alerts and AJAX requests in jQuery forms

I am looking to enhance my website by creating a form using PHP and jQuery. Currently, the form is placed in the footer of my website. However, I want to display the form results in a popup within the main section of the website without requiring a page ...

What are the steps for creating a div with a partially hidden element?

Is it possible to create a partially visible div on a webpage, similar to a footer, that slides up when clicked? This div will contain important information. I have managed to achieve this to some extent, but the issue I am facing is that the div doesn&ap ...

Utilizing Discord.js to import a variable from a method in a separate file

I'm working with two commands: join and disconnect. The join command allows the bot to join a voice channel using the joinVoiceChannel method, while the disconnect command removes the bot from the channel by utilizing the getVoiceConnection method: ...

Automating browser tasks with Python using Selenium's add-ons

chop = webdriver.ChromeOptions() prefs = {"download.default_directory" : DESIRE_SAVE_PATH} chop.add_experimental_option("prefs",prefs) chop.add_extension(FILE_LOCATION) driver = webdriver.Chrome(chromeDriverPath, chrome_options = chop) I have successfully ...

invoking a method of the grandparent from within the grandchild component

My components are nested three levels deep: <GrandParent /> <Parent /> <Child /> In the Child component, I have a button that, when double clicked, should call a function in the GrandParent component. <button @dblclick=&quo ...

Utilizing onBlur and onFocus events in React to implement a dynamic menu that shows or hides

Currently, I am in the process of mastering React and developing a small online electronic store. Within my project, there is a tab labeled "View Store". My goal is for a small, hidden column to appear when a user clicks on this tab, revealing text or imag ...