Create a canvas and include input boxes in an HTML document

I'm attempting to create a canvas line diagonally above two textboxes that are also positioned diagonally (similar to Samsung's pattern passcode) when a button is clicked, but I am facing difficulties in achieving this.

I have attempted to solve this by adjusting the input positions to absolute (resulting in some overlaps with other elements), however, as of now, I haven't found an optimal solution.

<!DOCTYPE html>
<html>
    <head>
        <style>
            * {
                z-index: 0;
            }
            canvas {
                z-index: 1;
                position: absolute;
            }
        </style>
    </head>
    <body>
    <div id="grid">
        <script>
            for(let i = 0; i < 2; i++){
                for(let j = 0; j < 2; j++){
                    document.getElementById("grid").innerHTML += `<input type="text" id="cell-${i}-${j}" max length="1" value="${2*i+j}" pattern="[A-Za-z]"/>`;
                }
                document.getElementById("grid").innerHTML += "<br/>";
            }
        </script>
        <button onclick="draw()" id="draw_btn">Draw Line</button>
    </div>
    <script>
        function draw(){
            const canvas = document.createElement("canvas");
            canvas.width = 200;
            canvas.height = 200;

            const ctx = canvas.getContext("2d");
            ctx.strokeStyle = "#ff0000";
            ctx.lineWidth = 10;
            ctx.beginPath();
            ctx.moveTo(0,0);
            ctx.lineTo(100,100);
            ctx.stroke();
            document.body.appendChild(canvas);
        }
    </script>
    </body>
</html>

Answer №1

One clever method involves setting the canvas to be absolutely positioned and placing it on top of the text boxes.

Absolutely positioned elements are placed relative to their closest absolute or relative parent. By applying position: relative to our #grid container and nesting the canvas inside, we can position it within the confines of the grid itself rather than the entire document.

for(let i = 0; i < 2; i++){
    for(let j = 0; j < 2; j++){
        document.getElementById("grid").innerHTML += `<input type="text" id="cell-${i}-${j}" maxlength="1" value="${2*i+j}" pattern="[A-Za-z]"/>`;
    }
    document.getElementById("grid").innerHTML += "<br/>";
}

function draw(){
    const canvas = document.createElement("canvas");
    canvas.width = 300;
    canvas.height = 40;

    const ctx = canvas.getContext("2d");
    ctx.strokeStyle = "#ff0000";
    ctx.lineWidth = 10;
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(300, 40);
    ctx.stroke();
    document.getElementById("grid").appendChild(canvas);
}
#grid {
  position: relative;
}

#grid input {
  width: 150px;
  height: 20px;
  box-sizing: border-box;
}

#grid canvas {
  position: absolute;
  left: 0;
  top: 0;
  
  pointer-events: none;
}
<div id="grid"></div>
<button onclick="draw()" id="draw_btn">Draw Line</button>

I also suggest adding

pointer-events: none;

to the canvas so that users can still interact with the input boxes below.

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

Tips for validating Angular form group input depending on the value of another input within the form?

I am facing an issue with form validation in my Angular version 8 application. I need to validate a form based on the following rules: If a file is uploaded (even if just clicking the button without selecting a file), then the Reason input is not required ...

Organize Dates in React Table

I need help with sorting the Date column in my code. Currently, the sorting is being done alphabetically. Here is the JSON data and code snippet: JSON [ { "date": "Jun-2022" }, { "date": "Jul-2022" } ...

Troubleshooting Problems with display:table and display:table-cell Alignment in Internet Explorer Versions 7 and 9

I have been struggling with the layout of a website that contains multiple columns. After extensive work, I believed I had everything properly aligned. Adobe BrowserLab seemed to confirm this, aside from various issues in IE6 and IE7 which I decided to ove ...

I am looking to showcase the JSON output on a ReactJS interface

Here is the output of my JSON data I am using the Map function in ReactJS to display elements from a JSON array. I have attempted the code below and encountered an error stating "Cannot read property '_currentElement' of null." Can someone pleas ...

Next.js app encounters a BSON error when using TypeORM

Currently, I am in the process of integrating TypeORM into my Next.js application. Despite utilizing the mysql2 driver and configuring 5 data sources, I am encountering a persistent BSON error: ./node_modules/typeorm/browser/driver/mongodb/bson.typings.js ...

Having difficulty retrieving the value of a variable obtained from the Google Distance Matrix function

Utilizing the Google distance matrix API to calculate the distance between two locations, I encountered an issue with global variable access. Despite changing the variable within a function, I found that I was unable to retrieve the updated value of the va ...

Use CSS to create a fullscreen animation for an element

Is there a way to animate a div element so that it expands to fit the screen when clicked without specifying an initial position? I need the div to be able to adjust dynamically within the screen. .box { width: 80px; height: 80px; background: red; ...

"Learn the process of converting HTML content into a string in an Android application and then displaying

I utilized this/this to Print Receipts in part of POS(Point of Sale) from EPSON Printer Obtaining data Json from URL (within the Json Object is html print template): { "response": { "status": "<table>.... </table>" } } Hence, ...

Understanding Namespacing in Vuex with Vue.js

Trying to organize modules' getters, mutations, and actions with namespacing can be a bit challenging. I came across this document, but it didn't provide clear enough information for me. // types.js // Constants for namespacing getters, actio ...

Navigating to a new page by selecting a row in a material-ui table

Within my project, there is a file labeled route-names.js containing the following entry: export const REVIEW_FORM_URL = '/custom-forms/:customFormId'; In one of my material-ui tables with multiple rows, clicking on a row reveals the id as ...

Disable the border and background colors in CloudFlare Turnstile

I have implemented the CloudFlare reCaptcha Turnstile and I am looking to modify the widget by removing the border and background color. I believe this customization can be achieved using CSS or Javascript. Thank you for any assistance! ...

Enhance Your jQuery Skills by Adding Custom Directories to Anchor Links

Can jQuery be used to add a custom folder name in front of all links on a webpage? For example, if the website has these links: <a href="/user/login">Login</a> <a href="/user/register">Register</a> <a href="/user/forum">Foru ...

What is the best way to cancel a request within an HTTP-interceptor?

Within an application, I have established the following URL structure for the API: // public public/url-xyz // private dashboard/url-xyz To avoid unnecessary requests, what is the most effective method for canceling a request? My current approach involv ...

Using the power of jQuery, execute a function only once when the element is clicked

My goal is to use jQuery's .one method to change the color of an element only once, even if clicked again. However, I am having trouble getting it to work properly. Here is my HTML: <!DOCTYPE html> <head> <meta charset="UTF-8"& ...

The checkbox labeled "Shipping Same as Billing" is not functioning correctly. I have included my JavaScript code below, can someone please help me identify what I am overlooking? (Only JavaScript code is provided; HTML is

I'm having trouble transferring data from a 'shipping' address to the 'billing' address section. I've included all my code, but nothing seems to copy over when the check box useShip is selected. All the HTML code is provided f ...

Discovering duplicates for properties within an array of objects in React.js and assigning a sequential number to that specific field

I am working with an array of objects where each object contains information like this: const myArr=[{name:"john",id:1}{name:"john",id:2}{name:"mary",id:3}] In the first 2 elements, the "name" property has duplicates with the value "john". How can I updat ...

Understanding JavaScript Prototypal Inheritance within ES5 Classes

I've been working on creating an XMLHttpRequest interceptor for Angular, encountering a roadblock when trying to intercept a third-party library that uses the XMLHttpRequest API. Although the solution below is functional, I've run into issues wit ...

Is there a way to change the labels of checkboxes within a table that is created dynamically?

I am new to JavaScript/jQuery and facing an issue with modifying checkbox labels in a dynamically generated table. <td> <input type="checkbox> <b>$18,000.00</b> ($18000+) Diamond Sponsor<br> <input type="checkbox> <b ...

What is the process for updating selenium-webdriver if it is not globally installed on my system?

After installing selenium-webdriver with the command npm install selenium-webdriver (without the -g option), I found that the usual instruction of running webdriver-manager update did not work since it was installed locally. What is the correct way to upd ...

Encountering an issue when trying to upload a file for the second time

I am currently working on a project where I need to upload an excel file and send it to an API using ReactJS. So far, I have been able to successfully send the file to the API. However, in my submit function, I want to reset the saved excel file from the s ...