xxxxxxxxxx
84
function getTextBoundingBox(_string, _x, _y) {
var texts = _string.split(/\n/g);
// 最も描画上で長い文字列を探す https://www.it-swarm-ja.tech/ja/javascript/%E9%85%8D%E5%88%97%E5%86%85%E3%81%A7%E6%9C%80%E3%82%82%E9%95%B7%E3%81%84%E6%96%87%E5%AD%97%E5%88%97%E3%82%92%E8%A6%8B%E3%81%A4%E3%81%91%E3%82%8B/972221201/
var longest = texts.sort(function(a, b) {
return textWidth(b) - textWidth(a); //b.length - a.length;
})[0];
var count = (_string.match(/\n/g) || []).length;
var return_data = {
x: _x,
y: _y,
w: textWidth(longest),
h: (count + 1) * textLeading()
}
return return_data;
}
function strIns(str, idx, val) {
var res = str.slice(0, idx) + val + str.slice(idx);
return res;
}
/*
文字列の長さに応じて自動で改行を入れる。
文字列の長さで直接改行する場合と、長さとスペースを鑑みて改行する2つの場合に対して対応する。なのでタイ語は無理。
*/
function insertNewline(_string, _w, _use_space) {
// 文字数で均等に改行する
if (_use_space == false) {
let total_width = textWidth(_string);
let count_new_line = total_width / _w;
let count_loop = _string.length / count_new_line;
for (let i = 1; i < count_new_line; i++) {
_string = strIns(_string, (count_loop * i + i), '\n');
}
}
// 最寄りのスペースで改行してあげる
else if (_use_space == true) {
let pos_start = 0;
let pos_end = _string.indexOf(' ', 0);
while (pos_end > 0) {
let str_oneline = _string.slice(pos_start, pos_end);
if (textWidth(str_oneline) > _w) {
_string = strIns(_string, pos_end + 1, '\n');
pos_start = pos_end + 2;
pos_end = _string.indexOf(' ', pos_start);
}
else{
pos_end = _string.indexOf(' ', pos_end+1);
}
}
}
return _string;
}
function textbox(_string, _font_size, _x, _y, _width_box, margin_x, margin_y,
_color, _background_color, _r, _use_space) {
textSize(_font_size);
rectMode(CORNER);
textAlign(LEFT, TOP);
let str_auto_new_line = _string;
// 文字列の横幅が指定ボックスサイズより大きくなる場合は事前に改行コードを自動挿入する
if (textWidth(_string) > _width_box) {
str_auto_new_line = insertNewline(_string, _width_box, _use_space);
}
// 指定した文字列で文字及びボックスを描画する
var box = getTextBoundingBox(str_auto_new_line, _x, _y);
noStroke();
fill(_background_color);
rect(box.x, box.y,
box.w + margin_x, box.h + margin_y,
_r);
fill(_color);
text(str_auto_new_line, _x + margin_x / 2, _y + margin_y / 2);
}