Positioning text in relation to an HTML canvas

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="800" height="450" style="border:1px solid #d3d3d3; background-color:#999999;">

Your browser does not support the HTML5 canvas tag.</canvas>

<script>

<!--normal canvas code-->

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

<!--code for the text line-->

ctx.font = "42px Arial";

<!--place the words in mid x position and in upper 1/6 of y position-->

var canvasxposition = (c.width/2)-(ctx.fillText.x/2)

var canvasyposition = c.height/6

ctx.fillText("Hello World",canvasxposition,canvasyposition);

</script>

</body>
</html>

I am utilizing a canvas element that will eventually be used to create an image. My goal is to center the text horizontally along the x-axis and position it at the top of the canvas vertically. Specifically, I want the text to appear one-sixth of the way down from the top.

Upon testing the provided code, I encountered an issue with the following line:

I require assistance in identifying the error within this line as my intention is to align the middle of the text along the y-axis with the middle of the canvas along the y-axis.

var canvasxposition = (c.width/2)-(ctx.fillText.x/2)

Answer №1

To perfectly center text horizontally, utilize context.textAlign

To align text vertically from its centerpoint, use context.textBaseline:

// Center text both horizontally and vertically
ctx.textAlign="center";
ctx.textBaseline="middle";

For a live demonstration and example code, visit: http://jsfiddle.net/m1erickson/nT37D/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    // Acquire references to the canvas and context
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    // Add crosshairs
    ctx.beginPath();
    ctx.moveTo(0,canvas.height/6);
    ctx.lineTo(canvas.width,canvas.height/6);
    ctx.moveTo(canvas.width/2,0);
    ctx.lineTo(canvas.width/2,canvas.height);
    ctx.stroke();

    // Align text both horizontally and vertically from its centerpoint
    ctx.textAlign="center";
    ctx.textBaseline="middle";

    // Display sample text
    ctx.font="18px arial";
    ctx.fillText("Hello World",canvas.width/2,canvas.height/6);

}); // end $(function(){});
</script>
</head>
<body>
    <h4>Centering text both horizontally and vertically within the text's centerpoint</h4>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

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

Avoiding duplicate form submissions in Struts2: Managing Success Messages Display

Is there a way to prevent multiple form submissions in Struts2? I am currently utilizing tokenSession (TokenSessionStoreInterceptor) for this purpose. However, it seems that this interceptor only considers the first request and ignores subsequent submits. ...

Using TypeScript, implement a function that is called when a React checkbox's state changes to true

Currently, I am experimenting with the react feature called onChange. My goal is to update local data by adding a value when a checkbox is selected. Conversely, when the checkbox is unselected, I just want to display the original data. However, I find that ...

Adjust the x-scroll to continue infinitely while deactivating the y-scroll

https://i.sstatic.net/KmDTe.png Is there a method in CSS to prevent vertical scrolling and have all the contents of a div positioned next to each other so that they extend beyond the visible browser window? I would like to enable horizontal scrolling to b ...

Creating tailored output data from a single table

Can you please assist me with a problem I am facing in generating output data using PHP and MySQL? Below is an image of my table: https://i.stack.imgur.com/zaieZ.png I would like the output to be displayed to the user in the following format: 1. Account ...

Difficulty integrating Bootstrap with JavaScript file in Visual Studio Code

I am attempting to incorporate a dynamic progress bar by utilizing Bootstrap's progressbar and creating a custom JavaScript file. The goal is to continuously adjust the width of the progress bar at regular intervals to give the appearance of a moving ...

Instructions on how to insert a single parenthesis into a string using Angular or another JavaScript function

Currently, I am employing Angular JS to handle the creation of a series of SQL test scripts. A JSON file holds various test scenarios, each scenario encompassing a set of projects to be tested: $scope.tests = [ { "Date": "12/31/2017", "Project": ...

fetch() operates successfully in Extension but encounters difficulties in Chrome Console/Snippet

I am currently facing an issue with my Chrome Extension. The extension performs a successful GET request, but when I try to replicate the same action in the Chrome Console or Snippets, I encounter errors. Here is a minimal example of the code I am using: f ...

What is the best way to display multiple canvases on one page?

Is it possible to draw multiple canvases in a single page using this code? I have successfully drawn a single canvas using the provided code. For each canvas, I have different y data and I need to display 6 canvases per page. How can I achieve this on a ...

The labels in production are getting cut off when creating a view in ASP .NET MVC

Upon viewing a Create View on my PC, I noticed that the main form and labels are adequately spaced: https://i.sstatic.net/1Q2bC.png However, once the website is deployed to IIS and accessed on the same PC with the same browser, everything appears cramped ...

Unspecified locale with Next.js router

Despite extensive research and multiple attempts, I have not been able to find a solution to my problem. That's why I am reaching out for help again. Currently, I am working on a local project and I would like to implement Internationalized Routing f ...

A tutorial on how to create the appearance of disabled buttons that look the same as enabled buttons through the use

My button includes a text field that is constantly disabled. I would like for the text field to appear as bright as it does when the button is enabled. After disabling the button, they both appear dimmer compared to others and the text field follows suit ...

What is the best way to group all matched objects from an array based on multiple keys?

const data = [ { amount:10, gameId:7 , consoleId:3, id: 1 }, { amount:5, gameId:18 ,consoleId:3, id: 2 }, { amount:5, gameId:18 ,consoleId:3, id: 3 }, { amount:10, gameId:7 ,consoleId:3, id: 4 ...

A custom script developed to detect the presence of the numeric combination "11" and promptly notify the

I am attempting to develop a unique chrome extension that detects typing errors in orders. For example, if the user accidentally types "11" instead of "1", an alert should be triggered. However, I am encountering an issue where the script is running in an ...

What is the best way to center align and add an icon to the header in Ionic?

How can I center align an "ion-ios-arrow-up" icon in the header of my Ionic app, similar to the concept shown below? This is my HTML template: <ion-view cache-view="false" view-title="Historical HPP"> <ion-nav-bar class="nav-title-slide-ios7 ...

In Node.js, when using the `new Date(year, month, date)` constructor, the date is automatically converted to UTC

var dateInCST; //Obtaining the current date in CST time zone. /*Trimming the time portion and retaining only the date.*/ var onlyDateInCST = new Date(dateInCST.getUTCFullYear(), dateInCST.getUTCMonth(), dateInCST.getUTCDate()); console.log(o ...

Reveal the hidden div by sliding it up from the bottom

I have a container with brown branches resembling the image, and I'm looking to hide it. When a button is clicked, I want it to reveal from the bottom to the top, almost like it's being unmasked. I've ruled out a typical bottom-up slide anim ...

Tips for aligning the timing of two CSS animations

I'm struggling to achieve a synchronized CSS animation where a progress bar fills up and a background changes simultaneously. For example, I want the progress bar to fill in 5000ms, with the background image changing every 5000ms as well. Despite se ...

Learn how to dynamically show the chosen option from a dropdown menu in input text fields using AngularJS

html file: <select ng-model="shipping" ng-options="shipping.shipping for shipping in shipAddress"> <option value=''>--Select Address --</option> </select> <form name="shippingForm" class="form-horizontal" role="form" ...

When the height is set to 100vh, the Div and Image appear misaligned vertically

Could someone explain why there is a vertical separation between the div and the image? <div style="height: 100vh; display: inline-block;width: 50%; background-color: blue">TEST </div><!-- --><img src="photos/openening.jpg" alt="SICK ...

Python Scrapy: Extracting live data from dynamic websites

I am attempting to extract data from . The tasks I want to accomplish are as follows: - Choose "Dentist" from the dropdown menu at the top of the page - Click on the search button - Observe that the information at the bottom of the page changes dynamica ...