Creating a Crest Effect in PHP

I am trying to figure out how to create the "Comb of Characters" effect, which exists in PDF, but does it in PHP for the standard text input field HTML = "text". Here, the text is distributed through the text field based on the maximum length of the text field and the width of the text field.

PDF definition:

Character Crest Distributes user-entered text evenly across the width of the text field.

Suppose I had 4 digits (the number of digits can be dynamic, so 2, 4, 8, 9, 10, 11, etc.). I wanted to propagate the following input field

<input type="text" style="width: 150px; height: 30px;" /> 

How can I do it? I am sure that mathematics is behind this, but I have no idea what mathematics is. Hoping that someone should have done this before. Please, no external libraries and nothing.

EDIT

While the RamRaider version works using javascript / CSS, I was hoping to get this in PHP.

The goal is for it to work as

 <input type="text" style="width: 150px; height: 30px;" value="<? echo $answer; ?>"/> 

So an example output would look like

 <input type="text" style="width: 150px; height: 30px;" value="1 2 3 4"/> 

I know that I will have to manually add spaces between each character, in which the math is very confusing.

+5
source share
1 answer

You can use the letter-spacing for css - if you did this in conjunction with javascript, you could make it dynamic for a different number of digits in the field

 var div=document.getElementById('kern'); var s=150;/* size of text field */ var l=div.value.length;/* number of characters */ div.style.letterSpacing=Math.ceil( s / l )+'px'; 
 #kern{ letter-spacing:calc( 150px / 4 ); } 
 <input id="kern" type="text" style="width: 150px; height: 30px;" value="1234" /> 

Not wanting to immediately admit defeat, the idea of ​​using canvas and the methods associated with it come to mind and lead to the following: it seems to work very well, I think.

  var txt=document.getElementById('kern'); var canvas=document.createElement('canvas'); var ctxt=canvas.getContext('2d'); ctxt.font='12px arial'; var s=parseInt( window.getComputedStyle( txt, null ).getPropertyValue( 'width' ) ); txt.onchange=function(){ ctxt.clearRect( 0, 0, canvas.width, canvas.height ); var w=ctxt.measureText( this.value ).width; space=Math.abs( ( s - w ) / this.value.length ); if( w < s ) this.style.letterSpacing=space+'px'; else { alert('The supplied text is naturally wider than the text input field can support'); } }.bind( txt ); 
 #kern{ font-size:12px; font-family:arial; letter-spacing:calc( 150px / 4 ); } 
 <input id="kern" type="text" style="width:150px; height:30px;" /> 
+2
source

Source: https://habr.com/ru/post/1257774/


All Articles