Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

กำหนดความกว้าง SVG Text Box หรือบังคับ Line Break หลัง x ตัวอักษร

ใช้ getBBox() วัดความกว้างข้อความ

เพิ่มคำทีละคำ ตรวจสอบความกว้าง หากเกิน Max Width ให้ใส่ Line Break (\n)

ตัวอย่าง Raphael.js

var paper = Raphael(500, 500);
var text = paper.text(100, 100).attr('text-anchor', 'start');
var maxWidth = 100;
var content = "Lorem ipsum dolor sit amet...";
var words = content.split(" ");
var tempText = "";

for (var i = 0; i < words.length; i++) {
    text.attr("text", tempText + " " + words[i]);
    if (text.getBBox().width > maxWidth) {
        tempText += "\n" + words[i]; // เว้นบรรทัดใหม่
    } else {
        tempText += " " + words[i];
    }
}
text.attr("text", tempText.substring(1));

getBBox() คืนค่า Bounding Box ของข้อความ ใช้วัดความกว้างได้แม่นยำ