preface

H5 development encountered several vertical text requirements, the implementation of the idea to sort out.

Some requirements for vertical text

  1. Input box style should be made into a vertical style;
  2. Canvas is used to generate pictures for users to save, and the text direction in the picture is vertical;
  3. Non – Chinese characters should be perpendicular to Chinese characters.

The project address

  • Project link: go.163.com/web/2019020…
  • Or scan:

DOM implements vertical text arrangement

The tag has no vertical attributes. The first attempt to modify the style was unsatisfactory. Finally, use the contenteditable property of HTML.

Attempted to modify the input style (failed)

You want to limit the width of the input field and the size of the text to make the text wrap automatically.

The key code

input{
    width: 30px;
    height: 250px;
    font-size: 30px;
}
Copy the code

Give up the reason

  • English character width is small, there will be a newline failure

Use HTMLcontenteditableAttributes instead of<input>(recommended)

The contenteditable property of HTML determines whether the content of an element is editable.

The key code

<div contenteditable="true" style="writing-mode: vertical-lr; writing-mode: tb-lr; "></div>
Copy the code
  • Use div instead of input
  • usecontenteditableProperty to make div editable
  • Using CSSwriting-modeProperty allows text to be arranged vertically

Use reasons

  • Non-chinese automatic rotation, better typography (fulfill the third point in requirements)

Canvas realizes vertical text arrangement

Canvas also does not have the property of vertical text, so I draw by traversing text.

The key code

let name; // Text content
let x = 657,y=170; // Coordinates where the text begins
let letterSpacing = 10; // Set the word spacing
for(let i = 0; i < this.name.length; i++){
    const str = this.name.slice(i,i+1).toString();
    if(str.match(/[A-Za-z0-9]/)&&(y<576)) {// Non-chinese character rotation
        ctx.save();
        ctx.translate(x,y);
        ctx.rotate(Math.PI/180*90);
        ctx.textBaseline = 'bottom';
        ctx.fillText(str,0.0);
        ctx.restore();
        y+=ctx.measureText(str).width+letterSpacing; // Calculate the text width
    }else if(str.match(/[\u4E00-\u9FA5]/)&&(y<576)){
        ctx.save();
        ctx.textBaseline = 'top';
        ctx.fillText(str,x,y);
        ctx.restore();
        y+=ctx.measureText(str).width+letterSpacing; // Calculate the text width}}Copy the code

Recommended reasons

  • Non-chinese automatic rotation, better typography (fulfill the third point in requirements)
  • usemeasureText()Calculate character width to make Chinese and English word spacing more harmonious