Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Comb of Characters effect in PHP

Tags:

html

php

I'm trying to find out how to create a "Comb of Characters" effect that exists in PDF, but doing it in PHP for a standard HTML input type="text field. This is where Text is spread across a textbox based on the max length of the textbox and the width of the textbox.

PDF definition:

Comb Of Characters Spreads the user-entered text evenly across the width of the text field.

Lets say I had 4 digits (the amount of digits can be dynamic so 2, 4, 8, 9, 10, 11 etc) I wanted to spread across the following input field

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

How would I go about doing this? I'm sure some math is behind this, but I have no clue what the math would be. Hoping someone has had to do this before. Please no external libraries or anything.

EDIT

While RamRaider version does work using javascript/CSS I was hoping to get this in PHP.

Goal would be to have it work like

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

So an example output would be like

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

I know I would have to manually add spaces in between each character which is where the math is very confusing.

like image 469
eqiz Avatar asked Oct 29 '22 19:10

eqiz


1 Answers

You can use the letter-spacing property of css - if you were to do that 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 admit defeat straight away the idea of using the canvas and it's associated methods came to mind and lead to the following - it seems to work pretty 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;" />
like image 160
Professor Abronsius Avatar answered Nov 09 '22 05:11

Professor Abronsius