Alignment of text varies between canvas and HTML

How can I ensure that the labels in both canvas and HTML display overlap exactly, regardless of font family and size? The current code fails to center text inside an area when switching between canvas and HTML view.

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
ctx.translate(canvas.width/2, canvas.height/2);
ctx.font = '64px Tahoma';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'BlueViolet';
ctx.fillText('Hello World!', 0, 0);
<canvas
  height="160"
  id="canvas"
  style="
    left: 0;
    opacity: 0.5;
    position: absolute;
    top: 0;
  "
  width="480"
></canvas>
<div
  style="
    align-items: center;
    color: FireBrick;
    display: flex;
    font-family: Tahoma;
    font-size: 64px;
    height: 160px;
    justify-content: center;
    left: 0;
    line-height: 1;
    opacity: 0.5;
    position: absolute;
    top: 0;
    width: 480px;
  "
>Hello World!</div>

Answer №1

Is it possible to adjust the ctx.translate function for proper functionality? If so, modify it to: canvas.height/2+6

ctx.translate(canvas.width/2, canvas.height/2+6);

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
ctx.translate(canvas.width/2, canvas.height/2+6);
ctx.font = '64px Tahoma';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'BlueViolet';
ctx.fillText('Hello World!', 0, 0);
<canvas
  height="160"
  id="canvas"
  style="
    left: 0;
    opacity: 0.5;
    position: absolute;
    top: 0;
  "
  width="480"
></canvas>
<div
  style="
    align-items: center;
    color: FireBrick;
    display: flex;
    font-family: Tahoma;
    font-size: 64px;
    height: 160px;
    justify-content: center;
    left: 0;
    line-height: 1;
    opacity: 0.5;
    position: absolute;
    top: 0;
    width: 480px;
  "
>Hello World!</div>

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

How can Angular be used for live search to provide precise search results even when the server does not return data in the expected sequence?

Currently, I am in the process of constructing a website for one of my clients. The search page on the site is designed to update search results as you type in the search bar - with each keystroke triggering a new search request. However, there's an i ...

Generate a list of users using Angular in an efficient manner

I am working on creating a user list similar to the image provided below. I am using Angular and Bootstrap for the basics of this project. However, my concern is how to efficiently handle a large number of users. If the user count exceeds 10k, what would b ...

Enhance your website with a stylish CSS jQuery menu that lets you toggle, slide

If you're curious about the code, take a look here! Here are some of the issues I'm facing: The div doesn't toggle to hide when clicked on itself, only when another one is clicked. (UPDATE: it actually won't toggle at all) When t ...

Creating a button in HTML that performs a POST request without redirecting involves using specific code techniques

Looking for a way to create an HTML button that triggers a POST request to a quick route with parameters passed through req.params. The challenge is preventing the button from redirecting me to the route when clicked, but instead staying on the same page w ...

Which component from the Bootstrap library would be best suited for my needs?

I am looking to create a basic 6-page website. Here is the code for my main page: <html> <style> .ali{ width:170px; text-align:center; } footer{ background:#333; color:#eee; font-size:11px; padding-top: 25px; p ...

Alter the website link in an HTML file as well as in the corresponding CSS and JavaScript

Is it possible for JQuery to alter URLs within a CSS or Javascript resource before they are loaded into the browser, or even as they load in the browser? URLs typically point to resources such as images and fonts. I have been considering this idea becaus ...

What is the best way to fill in predetermined HTML with information using jQuery?

Currently, I am working with several ajax forms that allow me to add rows of data dynamically using ajax. While the form submission is functioning correctly, I am having trouble figuring out the best way to append the newly inserted data into the database. ...

What is the best way to create space between floated elements and a cleared element?

I have a webpage with various floated boxes and a footer positioned at the bottom. The issue arises when trying to create space between the boxes and the footer without using margins. #main { max-width: 700px; margin: 0 auto; } .box { width: 46.6 ...

detect mouse click coordinates within an iframe that spans multiple domains

I am currently encountering an issue with tracking click position over a cross-domain iframe. Here is my current code: <div class="poin"> <iframe width="640" height="360" src="http://cross_domain" frameborder="0" allowfullscreen id="video">< ...

Looking for assistance navigating through a website's links using Selenium?

Trying to extract links from this webpage, specifically the ones listed in the footer. An example of what I'm dealing with: The goal is to scrape all links related to securities displayed in a table and then navigate through the footer to access more ...

Tips for keeping div and input tags selected even after a user clicks

I am working on a quiz script and I am trying to customize it so that when a user clicks on the div or input tags, they remain selected with a different background color. Currently, I have achieved changing the background color of the div when clicked, ...

Troubleshooting: Difficulty with jQuery's resize event handler not functioning properly with

I'm currently facing an issue where I want a divider to adjust its size when another divider changes size due to new content being loaded into it. However, even after binding the resize event handler to the divider that loads the content, the event do ...

Using PHP's modulus operator, you can dynamically apply CSS classes to a grid of images based on alternating patterns

Exploring the use of modulus to dynamically apply a CSS class to images displayed in a grid under different scenarios: Situation 1 In this situation, the goal is to target and apply a CSS class to middle images marked with *. Since the number of images ...

Discovering the name of an object property by locating its corresponding id

I am working with a basic JSON data structure where I need to retrieve the name from an object by comparing its ID. For example, if I have the number 2, I need to check if it matches any object's ID. If the ID is equal to 2, then I must fetch the corr ...

Injecting CSS styles into a webpage using a Chrome extension before the page has completely loaded to achieve instant customization

As a newcomer to creating Chrome (or other browser) extensions, I am working on developing one that applies custom CSS rules to specific page elements. Overall, it seems to be functioning as intended, but with some minor issues. One issue I have encounter ...

Aligning text to the center and having it displayed on either side of it

Hey there, I need help with the following: <div id='1'></div> <div id='2'></div> <div id='3'></div> I want to place a single word into each div. The width of each div should be ...

What is the best way to integrate Vuejs while maintaining the integrity of the HTML5 structure

According to the official Vuejs documentation, when it comes to the mounting point: The designated element only acts as a mounting point. Unlike in Vue 1.x, the mounted element will always be replaced with DOM generated by Vue. Therefore, it is advised ...

Determine the vertical dimension of an element through a JavaScript event listener

I've been working on creating an Apple-style image sequence scroller from a codepen demo. Here's the link to the original: https://codepen.io/jasprit-singh/pen/LYxzQjB My goal is to modify the JavaScript so that the scroll height is based on a p ...

The division element nested within a select tag

HTML: <div class="row"> <div class="form-group"> <div class="col-xs-10"> <label for="class_code_reservation">Class Code</label> <select type="text" class="form-control" id="class_code_reservation" na ...

retrieve the position of a descendant element in relation to its ancestor element

I'm encountering a challenge while attempting to solve this issue. I have elements representing a child, parent, and grandparent. My goal is to determine the offset position of the child (positioned absolutely) in relation to the grandparent. However, ...