Vertically Centering Text In Canvas Based on Font Size [duplicate] - javascript

This question already has answers here:
Center (proportional font) text in an HTML5 canvas
(7 answers)
Closed 6 years ago.
How do you vertically align text in canvas, based on the font size assigned? For instance, I have a rectangle with the height of 100px, and the variable textSize. My goal is to always vertically center the text inside of this specific rectangle.
Link to JS Fiddle
HTML
<canvas id="canvas" width="500" height="100"></canvas>
JS
var textSize = 40;
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineTo(0, 100);
ctx.lineTo(0, 0);
ctx.lineTo(500, 0);
ctx.lineTo(500, 100);
ctx.closePath();
ctx.fillStyle = "#000";
ctx.fill();
ctx.closePath();
// Text
ctx.save();
ctx.font = textSize + "px 'Oswald'";
ctx.fillStyle = "#fff";
ctx.textBaseline="middle";
ctx.fillText("Hello, World", 100, (100 - textSize)/2);
ctx.restore();
}
window.onload = init();

This answer might help
The canvas's context has a measureText function which you can use.

When you are using textBaseline= "middle" Why you are calculating the y coordinate considering textSize?
Probably
ctx.fillText("Hello, World", 100, 50);
This will do the job for you.

Related

HTML Canvas remove letter spacing on the beginning of a word

I have a canvas and I want to print words on it in horizontal and vertical orientation. The printing itself works fine but I have a somewhat annoying spacing at the beginning of the words, which becomes extremely visible on the vertical text like the EX on the example image.
I just created a little example which shows what I mean
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create a red line in position 150
ctx.strokeStyle = "red";
ctx.moveTo(150, 20);
ctx.lineTo(150, 170);
ctx.stroke();
ctx.font = "50px Arial";
// Show the different textAlign values
ctx.textAlign = "start";
ctx.fillText("EX", 150, 50);
ctx.textAlign = "end";
ctx.fillText("EX", 150, 100);
ctx.textAlign = "center";
ctx.fillText("EX", 150, 150);
<canvas id="myCanvas" width="300" height="200" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
Is there a way to place the beginning of the word at the point I am drawing to or is there a way to calculate the spacing at the beginning and then just subtract it from the starting point of the text?
The TextMetrics interface has actualBoundingBox[...] information that you can use to know by how much the actual bounding box is offset relatively to the textAlign and textBaseline lines.
So adding the measured actualBoundingBoxLeft to your horizontal position when writing LTR text with the "start" text-align will remove this gap.
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
const input = document.querySelector("input");
input.oninput = draw;
draw();
function draw() {
const txt = input.value;
ctx.clearRect(0, 0, c.width, c.height);
ctx.fillStyle = "black";
// Create a red line in position 150
ctx.strokeStyle = "red";
ctx.moveTo(150, 20);
ctx.lineTo(150, 180);
ctx.stroke();
ctx.font = "50px Arial";
ctx.textBaseline = "top"; // needed for the ascent and decsent measurements
// Show the original textAlign
ctx.textAlign = "start";
ctx.fillText(txt, 150, 30);
// fixed
ctx.fillStyle = "green";
const metrics = ctx.measureText(txt);
ctx.fillText(txt, 150 + metrics.actualBoundingBoxLeft, 110);
// Draw the box around our text
ctx.translate( 150, 110 );
const x = 0; // we already did offset by actualBoundingBoxLeft
const y = metrics.actualBoundingBoxAscent * -1;
const width = metrics.actualBoundingBoxRight + metrics.actualBoundingBoxLeft;
const height = metrics.actualBoundingBoxDescent + metrics.actualBoundingBoxAscent;
ctx.strokeRect(x, y, width, height);
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
<input value="Éxy"><br>
<canvas id="myCanvas" width="300" height="200" style="border:1px solid #d3d3d3;"></canvas>

Moving object to click even X and Y with canvas [duplicate]

This question already has an answer here:
HTML5 Canvas moving object to mouse click position
(1 answer)
Closed 6 years ago.
I was wondering is it possible to move a shape on the canvas to specific coordinates on the canvas from another set of coordinates. In this case is it possible to get the location of a mouse click and create an object that moves to that point over a specific amount of time? Thanks for your help in advance!
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x2=100,y2=100;
var dx=0,dy=0;
var counter=10;
canvas.width = canvas.height = 256;
var shape = {x:100, y:100, width : 50, height : 30};
function clear() {
ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
ctx.fillRect(0,0,canvas.width,canvas.height);
}
function draw(){
if(counter>0){
shape.x=shape.x+dx;
shape.y=shape.y+dy;
ctx.clearRect(0,0,256,256);
ctx.fillStyle = "red";
ctx.strokeStyle = "black";
ctx.fillRect(shape.x, shape.y, shape.width, shape.height);
ctx.strokeRect(shape.x, shape.y, shape.width,shape.height);
counter--;
setTimeout(draw,20)
}
}
canvas.addEventListener("click", function(e) {
clear();
x2=e.clientX;
y2=e.clientY;
dx=(x2-shape.x)/10;
dy=(y2-shape.y)/10;
counter=10;
draw();
});
draw();
</script>

Move canvas element into desired position

I've tried to look for the answer to this everywhere but I don't seem to find it. But I want to move the text created from an input to a specific position in the canvas, say, on the top centre.
The code runs like this: (JSFIDDLE)
<canvas id="canvas" style="background-color: #000" width="800px" height="300px"></canvas>
<input type="text" id="header-text" placeholder="Your Title">
Meanwhile, the js looks like:
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
document.getElementById('header-text').addEventListener('keyup', function() {
var stringTitle = document.getElementById('header-text').value;
console.log(stringTitle)
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#fff';
ctx.font = 'bold 36px Arial';
ctx.textAlign = 'center';
var text_title = stringTitle;
ctx.fillText(stringTitle, 15, canvas.height / 2 + 35);
});
Is there a way where I can move the text generated to the top centre? Thanks!
Well, you can use math to calculate the right position.
You used:
ctx.fillText(stringTitle, 15, canvas.height / 2 + 35);
so to change the text position to top center you can use something like this:
ctx.fillText(stringTitle, canvas.width/2, canvas.height / 8 + 35);
To have text in top center:
ctx.fillText(stringTitle, canvas.width / 2, 36);
Where 36 is size of your font (height).
If you need more precision while positioning text horizontally, you could use
CanvasRenderingContext2D.measureText().

Fill Closed Are using HTML5 Canvas

I have drawn some graphics using html5 canvas.
var ctx = document.getElementById('canvas').getContext('2d');
ctx.stroke = "red";
ctx.beginPath();
ctx.moveTo(30, 30);
ctx.lineTo(150, 150);
ctx.bezierCurveTo(60, 70, 60, 70, 70, 150);
ctx.lineTo(30, 30);
ctx.fill();
When I click the canvas area, if the click point is in a closed area, I would like to fill the closed area with color red.
Help me, please
ctx.fillStyle = 'red';
http://jsfiddle.net/zsal/FfdCe/2/
Here is a jsfiddle with your canvas filled red on hover.

How to detect if a mouse pointer hits a line already drawn on an HTML 5 canvas

I am trying to figure out how one can detect if the user's mouse hits a line on an HTML 5 canvas with jQuery.
Here is the code that generates the canvas lines:
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
window.onload = function(){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(40,0);
ctx.lineTo(40,360);
ctx.stroke();
ctx.moveTo(80,400);
ctx.lineTo(80,40);
ctx.stroke();
ctx.moveTo(120,0);
ctx.lineTo(120,360);
ctx.stroke();
ctx.moveTo(160,400);
ctx.lineTo(160,40);
ctx.stroke();
};
</script>
I'm using a modified jQuery script that I actually found in another question on here, but now I can't figure out how to detect the line, mainly the difference in color from white to black, in the canvas. I know that this can be done with images, but I haven't seen anyone with something like this.
I guess my real question is, is there a way to detect color changes on a canvas element with jQuery?
Its possible to do with javascript. In fact you aren't using any jQuery in your example above. An easy way to do it is by grabbing the pixel data from the canvas, and checking the alpha at the specified x and y position. If the alpha isn't set to 0, then you have something drawn on the canvas. Below is a function I put together real quick that does that.
Live Demo
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 400;
height = 400;
canvas.width = canvas.height = 200;
// draw
ctx.moveTo(40, 0);
ctx.lineTo(40, 360);
ctx.stroke();
ctx.moveTo(80, 400);
ctx.lineTo(80, 40);
ctx.stroke();
ctx.moveTo(120, 0);
ctx.lineTo(120, 360);
ctx.stroke();
ctx.moveTo(160, 400);
ctx.lineTo(160, 40);
ctx.stroke();
function detectLine(x, y) {
var imageData = ctx.getImageData(0, 0, width, height),
inputData = imageData.data,
pData = (~~x + (~~y * width)) * 4;
if (inputData[pData + 3]) {
return true;
}
return false;
}
canvas.addEventListener("mousemove", function(e){
var x = e.pageX,
y = e.pageY;
console.log(detectLine(x, y));
});
console.log(detectLine(40, 100));
console.log(detectLine(200, 200));

Categories