What is preventing the Canvas from showing up on the bootstrap table?

I'm facing an issue with displaying a writable Canvas inside a Bootstrap table. When I place the Canvas within the table, the content doesn't show up properly or sometimes not at all. However, when I move the Canvas out of the table and place it in either the container or body, it works perfectly fine. Below is the code snippet for reference. Can anyone help me understand why this happens and suggest a solution? Thank you in advance.

$(document).ready(function() {
    function createCanvas(parent, width, height) {
    var canvas = document.getElementById("inputCanvas");
    canvas.context = canvas.getContext('2d');
    return canvas;
  }

  function init(container, width, height, fillColor) {
    var canvas = createCanvas(container, width, height);
    var ctx = canvas.context;
    ctx.fillCircle = function(x, y, radius, fillColor) {
      this.fillStyle = fillColor;
      this.beginPath();
      this.moveTo(x, y);
      this.arc(x, y, radius, 0, Math.PI * 2, false);
      this.fill();
    };
    ctx.clearTo = function(fillColor) {
      ctx.fillStyle = fillColor;
      ctx.fillRect(0, 0, width, height);
    };
    ctx.clearTo("#fff");

    canvas.onmousemove = function(e) {
      if (!canvas.isDrawing) {
        return;
      }
      var x = e.pageX - this.offsetLeft;
      var y = e.pageY - this.offsetTop;
      var radius = 10;
      var fillColor = 'rgb(102,153,255)';
      ctx.fillCircle(x, y, radius, fillColor);
    };
    canvas.onmousedown = function(e) {
      canvas.isDrawing = true;
    };
    canvas.onmouseup = function(e) {
      canvas.isDrawing = false;
    };
  }

  var container = document.getElementById('inputCanvas');
  init(container, 200, 200, '#dddd');

});
#inputCanvas{
    border: 5px solid rgb(102,153,255);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

<body>
<div class="container">
     <table class="table table-bordered">
        <thead>
        <tr>
            <th scope="col" style="text-align:center">Pick an image File</th>
            <th scope="col" style="text-align:center">Draw a Number</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>
                <form method="post" action="/upload" enctype="multipart/form-data">
                    <div class="d-flex justify-content-center">
                        <div class="form-group">
                            <input type="file" class="form-control-file" name="img" accept="image/*" id="img"
                                   aria-describedby="fileHelpId">
                        </div>
                    </div>
                    <div class="col text-center">
                        <input type="submit" value="Submit" class="btn btn-primary">
                    </div>
                </form>
            </td>
            <td>
               <canvas id="inputCanvas" width="400" height="400"></canvas>
            </td>
        </tr>
        <tr>
            <th colspan="2" style="text-align:center">
                Predicted Number
            </th>
        </tr>
        </tbody>
    </table>
</div>

Answer №1

Modify:

var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;

To:

var xy = this.getBoundingClientRect();
      
  var x = e.pageX - xy.left - window.scrollX;
  var y = e.pageY - xy.top - window.scrollY;

The rationale behind why this.offsetLeft fails to function within a table is because it retrieves the offsetLeft relative to its parent rather than relative to the browser window.

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

What is the rationale behind axios adding the current URL to API requests in Laravel or React?

I am currently working on a project that involves Laravel, React, and Redux. The following code snippet is from a function called by a Redux Saga worker: function fetchItems() { return axios.get('/api/items').then(response => response.dat ...

WebDriver is now being permitted by Chrome to access insecure pages

When using Chrome 62, Chrome Driver 2.33, and WebDriver 3.6.0, I have noticed that Chrome allows pages to load with bad SSL certificates. Even though the URL bar displays "Not Secure," the page still loads without any issues. Strangely, if I navigate to th ...

Obtaining complete address details for every location on the Google Maps route

In my Windows Forms application using VB.NET, users can search addresses on Google Maps and view directions between two points. I've implemented a feature that allows users to adjust the route as they wish. Now, I'm wondering if there is a way fo ...

Discovering essential parameters in JavaScript callbacks

As I delve into the world of JavaScript, particularly node.js, I find myself struggling to grasp the required parameters for callbacks. For instance, when creating a route using Express, I can do the following: app.get('/', function() { conso ...

How can I modify the container to prevent the Bootstrap dropdown from being clipped by overflow:hidden settings?

With bootstrap, I encountered a situation where dropdown menus are being clipped by my <div> with overflow: hidden. How can I address this issue without incurring high costs? One potential solution might be to change the container of all dropdowns wi ...

Encountering a problem with updating a specific data attribute through an ajax

My goal is to retrieve data using ajax and update an attribute in a div called data-used. However, I am encountering an issue where the attribute does not change and the console displays the following error message: TypeError: "#powerv1".data is not a f ...

Switching from a click event to a hover event in JavaScript

I've been experimenting with animating a burger bar on hover and came across an example online that I managed to adapt for mouseenter functionality. However, I'm struggling to make it revert back to the burger bar shape once the mouse leaves on m ...

Organize an array containing nested objects within other objects

I'm stuck with sorting this array: [ ["name1", { count: 20 }], ["name2", { count: 10 }] ] Is there a way to sort this array based on the count values? My attempt using the sort function was unsuccessful, const sort = Array.sort((a, b) => b ...

Ways to swap out a React component for a different one after modifying its state

I'm relatively new to React and I am currently working on a project where I need to display a large image that takes 3-4 seconds to load. To enhance user experience, I plan to implement a loader using the ReactImage component available at https://www. ...

What's the simplest approach for incorporating a database into an HTML document?

After completing my project website with html files, css, and javascript, I decided to enhance it by adding a login functionality and other features. However, I am now faced with the challenge of deciding which platform to use. I came across Django in Py ...

Displaying a message text upon successful AJAX request

I have a web page with an AJAX request that updates data in the database. After the update, I want to display a message to the user on the webpage confirming that the data has been successfully updated. However, currently, no message is being displayed and ...

The Ajax success callback contains various key-value pairs within $.fn

Currently, I am utilizing a jQuery library called jcarousellite. This library adds the constructor jCarouselLite to the prototype of the $/jQuery constructor. $.fn.jCarouselLite=function(){ /*"LOTS OF CODE HERE"*/ } On document ready event ($(document).r ...

Leveraging the power of Auth0 and Prisma in aggregating user data

In my current project, I am developing a Next.js application with Auth0 as the authentication system. Users are authenticated using the standard middleware: import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge'; export default wi ...

The draggable() function in jQuery and the ng-repeat directive in Angular make for a powerful combination

The code snippet I have is as follows. HTML <div ng-repeat="item in canvasElements" id="declareContainer"> {{item}} </div> Javascript (Angular) (function(){ //angular module var dataElements = angular.module('dataElements' ...

Angular 6: Issue TS2339 - The attribute 'value' is not recognized on the 'HTMLElement' type

I have a textarea on my website that allows users to submit comments. I want to automatically capture the date and time when the comment is submitted, and then save it in a JSON format along with the added comment: After a comment is submitted, I would li ...

Transform JSON data into a collection of maps using Javascript

I need to include some JSON data in a response entity for it to be passed. Here is an example of the JSON: {"headers":{"Content-Type":["application/json; charset=utf-8"]},"body":"\"[{\\\"name\\\":\\\"BFF&b ...

What are some techniques for styling a field when the div id is not specified?

I need to customize a data field within a table, but I am unable to locate or identify its div ID. Here is the page source: <tbody> <tr> <td style="font-size:12px; text-align:center;" name=""> <div sty ...

"Challenges with AngularJS and KineticJS canvas toDataUrl function in Chrome browser when dealing with images from the same domain

I've been trying to find a solution to this issue for the past couple of days. The common response I come across is "it works on the server but not on the local machine," but in my case, it doesn't work on either... I've extracted the neces ...

Mastering the use of Quasar variables in your scss styles is crucial for optimizing your

I recently set up a project using Vue3 and Quasar by running vue add quasar. However, I am struggling to figure out how to utilize Quasar sass/scss variables. According to the documentation, I should use the following syntax: <style lang="scss&quo ...

Creating Karma and Jasmine unit tests for an Angular service that relies on another module

I have gone through numerous articles but still cannot grasp the process of creating it. There is a particular module (“A”) that includes a service (“B”) which contains a specific function (“C”). This function uses another function (“E”) f ...