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

Pagination does not refresh when conducting a search

HTML Code: The following HTML code displays a table with a search filter. . . <input type="search" ng-model="search.$" /> <table class="table table-striped table-bordered"> <thead> <tr> <th><a href ...

Detecting the scroll events of elements with the overflow:hidden property

Looking to synchronize scrolling between two different panels or divs? In one element, there's an overflow: auto while the other has overflow: hidden (trying to mimic a grid with frozen columns). I've managed to sync the scroll when it occurs w ...

Adjust the hue of the X axis labels to display a variety of colors within Chart.js

Utilizing Chart.js for my bar chart. The X axis labels contain 4 lines, and I want to change the color of each line individually rather than having all values in one color. var barChartData = { labels: [["Injection", 10, 20], // Change the color here ...

"Attempting to access a variable defined in one pipe results in it being undefined in a

Currently, I am utilizing gulp to process pages for a website. Some of these pages are PHP files, however, after going through the template engine, they all end up with a .html file extension. My intention is to add a property to each file indicating if it ...

Troubleshooting problem with ion-input in Ionic 3 regarding the keyboard issue

Issue with Keyboard Overlaying Button In my ionic3 app, I am facing an issue where the keyboard overlaps the "Registrarse" button when it is open, as shown in the image. The button is positioned at the bottom of the ion-content using CSS rules such as pos ...

What is the significance of the "rc" within the version structure of an npm package?

Can someone help me understand what the rc in 2.2.0-rc.0 signifies? I'm curious if it indicates that this version is ready for production use. ...

Enrollment in the course is conditional on two words being a perfect match

I have a concept in mind, but I'm struggling to piece it together. I have bits of different methods that just don't seem to align. That's why I'm reaching out for your expertise. Let's say I have 3 content containers with the clas ...

Exploring Several Images and Videos in Angular

I'm experiencing a challenge with displaying multiple images and videos in my Angular application. To differentiate between the two types of files, I use the "format" variable. Check out Stackblitz export class AppComponent { urls; format; on ...

Saving form blueprints and operations in a Data Repository

My team and I are working on a sophisticated web application with a complex back end. We have hundreds of form schemas paired with their corresponding return functions, which are triggered upon form submission. These JSON objects dynamically generate forms ...

Using an HTML5 image icon as an input placeholder

Is there a way to incorporate an image icon into an input placeholder and have it disappear when the user starts typing, across all browsers? In trying to achieve this, I successfully implemented a solution for webkit (Safari+Chrome) using ::-webkit-input ...

Ways to collect email address or name from an email message

Suppose I send an email to someone with a link at the bottom. The text of the link might be something like click me. When the user clicks on this link, they will be directed to a webpage. On this webpage, a message saying "Thank you" will be displayed a ...

The failure of the ajax call to encapsulate is likely due to issues with object visibility

Having some trouble with a piece of code meant to run smoothly on Firefox 3.6. The issue arises when the variable this.xmlhttp, defined in STEP2 and used in STEP3, seems to be operating in different variable environments. Even though I expect the two usa ...

Remove the concluding statement from the HTML string if it exceeds the capacity of the iPhone's webView

I have an array of content with certain sections in bold. The bold parts can be located anywhere within the text, so I am utilizing a webView to display an HTML string with appropriate bold tags. However, I am encountering issues where the webViews do not ...

In order to enhance your programming skills, avoid hard coding functions and ensure that data is returned after binding changes

I am trying to create a method where I can provide a DOM as a parameter and retrieve data from image_preview. The goal is to make image_preview reusable instead of hardcoding it inside the function. Additionally, I want to separate image_preview.model() an ...

Sort Messages By Date Created

While using Vue, I encountered a general JavaScript question. I am fetching cat messages from an API for a chat interface. The initial call returns an array of objects where each object represents a chat message: data: [ {id: 1, created_at: "2022-05 ...

Utilizing CSS to Display a Variety of Colors within a Text String

Is it possible to style different words in a sentence with various colors using only CSS, without using the span element? For instance, how can I make the word "Red" appear in red, "Blue" in blue, and "Green" in green within an h1 tag? ...

Quiz results are incorrect

I've been working on creating a quiz application using JavaScript only, but I'm encountering an issue with the scoring. Initially, I set the correct variable to 0 and intended to increment it by 1 each time a correct answer is selected. However, ...

Unexpectedly, the child component within the modal in React Native has been resetting to its default state

In my setup, there is a parent component called LeagueSelect and a child component known as TeamSelect. LeagueSelect functions as a React Native modal that can be adjusted accordingly. An interesting observation I've made is that when I open the Lea ...

Softening the edges of a table

Could you assist me in rounding the corners of my table? I attempted using the basic border-radius, however, it only separated the border at the corners. Do you think this issue is due to my browser (Firefox) or could it be a bug? You can view my Jsfiddl ...

Invoke a function from a page that has been reloaded using Ajax

After making an Ajax request to reload a page, I need to trigger a JavaScript function on the main page based on certain database conditions. This is necessary because I require some variables from the main page for the function. PHP code: if($reset_regi ...