Curved Text inside a circle and center to bottom center - javascript

I have a circle, and i need to have text inside the circle, that follows the circles path. I have found this other question: Wrapping a text around a circular element
However, i was not able to achieve what i'm trying to do. My text has a dynamic length, and i need it to be always centered to the bottom center of the circle, and wrap "upwards" on both sides, if that makes sense. I have tried the svg approach, but when the text is too long, it gets cut off. What would be the best approach to do this?
The text would be orange here (dynamic length), and it needs to centered to the bottom of the circle (blue dot)

Having tried positioning text with middle in the svg I found it cut the text if the text was following a path - as in the question.
Could not find a solution for this in SVG and/or CSS so resorted to a method with JS and show it here just in case of use as an interim measure.
In this snippet, the width of the text is found and the amount the SVG needs to rotate in order to put the mid point of the text at the bottom center of the circle is calculated:
const textPath = document.querySelector('textPath');
const temp = document.createElement('div');
temp.innerHTML = textPath.innerHTML;
temp.style.display = 'inline-block';
temp.style.fontSize = '20px';
document.body.append(temp);
const w = temp.offsetWidth;
document.body.removeChild(temp);
const circumference = Math.PI * 200;
document.querySelector('svg').style.transform = 'rotate(' + Number((180 * w / circumference) - 90) + 'deg)';
.qr--label {
font-size: 20px;
margin: 0 0 -15px 0;
text-align: center;
}
<div class="qr">
<div>
<svg width="220" height="220">
<path fill="white" d="M0,110a110,110 0 1,0 220,0a110,110 0 1,0 -220,0"/>
<path fill="none" id="innerCircle" d="M10,110a100,100 0 1,0 200,0a100,100 0 1,0 -200,0"/>
<text>
<textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#innerCircle" class="qr--label">
Some dynamic text here
</textPath>
</text>
</svg>
</div>
</div>

Related

SVG polygon unable to highlight

I'm trying to highlight a specific polygon inside a SVG, by changing its stroke color.
Unfortunately, one side is completely covered by the second polygon's stroke.
I have tried to bring it to the front with z index, but no luck.
<button id="b1" type="button">1st</button>
<svg viewBox="0 0 1240 1000">
<g>
<polygon class="map__1" id="pol1" points="106.75,266 4,266 4,135 106.75,135 106.75,266" data-id="1">
</polygon>
<polygon class="map__2" points="178.25,168.655 106.75,240 106.75,135 145.75,135 178.25,168.655" data-id="2"></polygon>
</g>
</svg>
js
let btn1 = document.getElementById("b1");
let pol1 = document.getElementById("pol1");
btn1.addEventListener("click", myFunction);
function myFunction() {
pol1.style.stroke = "#fc0303";
}
css
.map__1, .map__2 {
stroke: #000;
stroke-width: 5px;
stroke-miterlimit: 10;
fill: #6e6e6e;
}
Here's the fiddle: https://jsfiddle.net/tfzbjxL3/
I also tried with the outline property, but it doesn't fits on other kind of polygons but squares.
Is there any way that I could manage to do this?
Thanks!
You'd need to change the order of the polygons i.e using appendChild:
function myFunction() {
pol1.style.stroke = "#fc0303";
pol1.parentNode.appendChild(pol1);
}
JSFiddle

How to measure width of a string in SVG before creating the actual SVG element (in Angular)

I want to create a SVG element, which include a list of node, each node is a rectangle with a text inside:
<svg class="chart" width="420" height="150" aria-labelledby="title" role="img">
<ng-container *ngFor="let item of listNode">
<g viewBox="0 0 56 18">
<rect [attr.width]="item.w" [attr.height]="2*item.h" fill="white"></rect>
<text [attr.x]="item.x" [attr.y]="item.y" text-anchor="middle" font-family="Meiryo" font-size="item.h"
fill="black">{{item.label}}</text>
</g>
</ng-container>
</svg>
But I want to put the text is in center of the rectangle (both vertically and horizontally). To do this, I think I need to measure the width of text before creating the SVG element.
I tried to use the below function to measure text size:
getTextWidth(text, fontSize, fontFace) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = fontSize + 'px ' + fontFace;
return context.measureText(text).width;
}
But the result is not correct.
So, Is there any way to measure size of SVG text element before creating the real element (like my getTextWidth function), or is there any other way to create rectangle with text is exactly in center.
There are many ways to measure the text width and height but if you have the text itself and its font properties, you already have it.
1) Let's suppose you don't want to do the math, you can use HTMLElement properties.
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
const span = document.createElement('span')
document.body.append(span)
span.style = 'font-family: Arial; font-size: 14px'
span.innerHTML = 'TEXT'
document.body.textContent =
`width: ${span.offsetWidth} height: ${span.offsetHeight}`
span.remove()
</script>
</body>
</html>
Note: don't forget to append your element.
2) Use those dimensions to set your rect dimensions (add extra if you want padding) and set your text in the middle like so:
<text
style="font-family: Arial; font-size: 14px"
x="50%"
y="50%"
dominant-baseline="middle"
text-anchor="middle">TEXT</text>
Note: use always the same style in your text.
Hope this help :)

HTML and SVG how to move only one endpoint of a line with mouse click?

I've been trying to figure out a way to move just one end of a line, but it keep changing the container and thus redrawing the entire line and moving it.
Here's a js fiddle: https://jsfiddle.net/h2nwygu8/1/
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Review Race</title>
</head>
<body>
<div class="wrapper">
<section>
<h1>Line Test</h1>
<div id="canvas" style="width: 960px; height:410px; border: 4px solid lime;">
<svg id="svgContainer" xmlns="http://www.w3.org/2000/svg" version="1.1" style="position: absolute; top:95px; width:960px; height:410px;">
<line id="start_line" x1="10" y1="0" x2="10" y2="960" style="stroke:rgb(255,0,0);stroke-width:3;" />
</svg>
</div>
</section>
</div>
</body>
</html>
and javascript:
function placeLine(e) {
var d = document.getElementById('start_line');
posY = e.clientY;
posX = e.clientX;
d.setAttribute("y1", posY)
d.setAttribute("x1", posX)
}
document.addEventListener("click", placeLine);
what I would like to do is have the top of the red line move around over the green box to the mouse x,y position. The bottom of the line should not move. However with each click the containers are changing and moving the entire line. You can also see there are a few issues with the offsets with the mouse x,y and the line. The only restriction is that the line needs to be able to layer over the top of the container with the green boundary.
What's the best way to do this? Thanks.
You've mixed up the height and width with regards to the x2 and y2 properties. It should start working more like you expect if you change y2 to be equal to your height (410px).
See: https://jsfiddle.net/zukrtpyg/.
HTML:
<div id="canvas" style="width: 960px; height:410px; border: 4px solid lime;">
<svg id="svgContainer" xmlns="http://www.w3.org/2000/svg" version="1.1" style="width:960px; height:410px;">
<line id="start_line" x1="0" y1="0" x2="0" y2="410" style="stroke:rgb(255,0,0);stroke-width:3;" />
</svg>
</div>
Javascript:
function placeLine(e) {
var d = document.getElementById('start_line');
posY = e.offsetY;
posX = e.offsetX;
d.setAttribute("y1", posY)
d.setAttribute("x1", posX)
}
document.getElementById('canvas').addEventListener("click", placeLine);
I've also removed the top and position declarations on the canvas element, these were causing the line to extend past the green border on the bottom.
Lastly, I've changed the click listener to be on the canvas element, that way you can use the events' offsetX and offsetY to position the line in relation to the canvas element, which is what the path coordinates are mapped to in the first place.
Using the clientX and clientY positions tries to place it in relation to the page, which doesn't map up with the position you want it to be on the canvas.
You can actually still use the clientX and clientY positions, you just have to compensate with the x and y position of the canvas element in relation to the page. You can find these out using Element.getBoundingClientRect(). See https://jsfiddle.net/th0aLcx0/ for an example.

Partially fill a shape's border with colour

I am trying to create a progress effect whereby colour fills a DOM object's border (or possibly background). The image attached should give you a better idea of what I'm going for. I have achieved the current result by adding an object with a solid background colour over the grey lines and setting its height. This object has mix-blend-mode: color-burn; applied to it which is why it only colours the grey lines underneath it.
This works okay, but ruins the anti aliasing around the circle, and also the produced colour is unpredictable (changes depending on the colour of the lines).
I feel there must be a better way of achieving this, perhaps with the canvas element. Could someone point me in the right direction please?
Thanks in advance!
This should be possible to do with Canvas and may even be possible with CSS itself by playing with multiple elements etc but I would definitely recommend you to use SVG. SVG offers a lot of benefits in terms of how easy it is to code, maintain and also produce responsive outputs (unlike Canvas which tends to become pixelated when scaled).
The following are the components:
A rect element which is the same size as the parent svg and has a linear-gradient fill. The gradient has two colors - one is the base (light gray) and the other is the progress (cyan-ish).
A mask which is applied on the rect element. The mask has a path which is nothing but the line and the circle. When the mask is applied to the rect, only this path would show through the actual background (or fill) of the rect, the rest of the area would be masked out by the other rect which is added inside the mask.
The mask also has a text element to show the progress value.
The linear-gradient has the stop offset set in such a way that it is equal to the progress. By changing the offset, we can always make sure that the path shows the progress fill only for the required length and the base (light gray) for the rest.
window.onload = function() {
var progress = document.querySelector('#progress'),
base = document.querySelector('#base'),
prgText = document.querySelector('#prg-text'),
prgInput = document.querySelector('#prg-input');
prgInput.addEventListener('change', function() {
prgText.textContent = this.value + '%';
progress.setAttribute('offset', this.value + '%');
base.setAttribute('offset', this.value + '%');
});
}
svg {
width: 200px;
height: 300px;
}
path {
stroke-width: 4;
}
#rect {
fill: url(#grad);
mask: url(#path);
}
/* just for demo */
.controls {
position: absolute;
top: 0;
right: 0;
height: 100px;
line-height: 100px;
border: 1px solid;
}
.controls * {
vertical-align: middle;
}
body {
background-image: radial-gradient(circle, #3F9CBA 0%, #153346 100%);
}
<svg viewBox='0 0 200 300' id='shape-container'>
<linearGradient id='grad' gradientTransform='rotate(90 0 0)'>
<stop offset='50%' stop-color='rgb(0,218,235)' id='progress' />
<stop offset='50%' stop-color='rgb(238,238,238)' id='base' />
</linearGradient>
<mask id='path' maskUnits='userSpaceOnUse' x='0' y='0' width='200' height='300'>
<rect x='0' y='0' width='200' height='300' fill='black' />
<path d='M100,0 100,100 A50,50 0 0,0 100,200 L100,300 M100,200 A50,50 0 1,0 100,100' stroke='white' />
<text id='prg-text' x='100' y='155' font-size='20' text-anchor='middle' fill='white'>50%</text>
</mask>
<rect id='rect' x='0' y='0' width='200' height='300' />
</svg>
<!-- just for demo -->
<div class='controls'>
<label>Set Progress:</label>
<input type='range' id='prg-input' min='0' max='100' value='50' />
</div>
If you are new to SVG you can refer to the MDN Docs (links provided below) for more information about the elements, their attributes and values.
SVG Mask Element
SVG Tutorial on Paths

Basic vertical SVG line

I cannot seem to find a good, working example / tutorial of how to draw a simple, vertical line which animates gradually on scroll from nothing to a full line.
I have the code below which draws a horizontal line, but I cannot seem to successfully change this to a vertical line that continues to animate.
HTML:
<svg id="mySVG">
<path fill="none" stroke="red" stroke-width="3" id="triangle" d="M1 0 L75 0"/>
</svg>
CSS:
#mySVG {
position: fixed;
top: 15%;
width: 400px;
height: 210px;
margin-left:0px;
}
JS:
<script>
// Get the id of the <path> element and the length of <path>
var triangle = document.getElementById("triangle");
var length = triangle.getTotalLength();
// The start position of the drawing
triangle.style.strokeDasharray = length;
// Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw
triangle.style.strokeDashoffset = length;
// Find scroll percentage on scroll (using cross-browser properties), and offset dash same amount as percentage scrolled
window.addEventListener("scroll", myFunction);
function myFunction() {
var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
var draw = length * scrollpercent;
// Reverse the drawing (when scrolling upwards)
triangle.style.strokeDashoffset = length - draw;
}
</script>
It should just be a matter of making your line vertical, as follows:
<svg id="mySVG">
<path fill="none" stroke="red" stroke-width="3" id="triangle" d="M1 0 L1 75"/>
</svg>
What happens when you do that?
thanks for all your replies - I ended up using CSS transitions as this seem to work better.

Categories

Resources