检测canvas元素是否在画布边界之外

DS9*_*DS9 10 javascript php svg canvas fabricjs

我工作的一个项目中,管理员可以创建一个名片模板,使他们能够像插入占位符变量{first_name},{last_name},{website}等于是一个卡将通过使用户填写自己的名字,姓氏等,所以基本上占位符创建将被用户提供的实际内容所取代.为此,我将从管理员创建的模板创建一个SVG图像,并将这些占位符变量替换为服务器端的用户数据.

问题在于,如果用户提供的内容太长,则可能会延伸到画布边界之外,因此在打印实际卡时可能会被切断.

有没有办法检测到,在替换占位符后,canvas元素会延伸到画布边界之外?如果是这样,有没有办法找到该元素并使其收缩直到它适合边界?基本上,我想类似这样,但在服务器端.

这是我用来生成SVG图像的一些示例代码:

$message_string = array('{first_name}','{last_name}');
$replace_string = array('Fist Name of User','Last Name Of User');
$front_svg_url = $svg_url.$res_code[0]['front_side_svg_image'];
$front_raw_svg = file_get_contents($front_svg_url);
$front_side_svg = str_ireplace($message_string, $replace_string, $front_raw_svg);
$file_name = uniqid($prefix).".svg";
$file_handle = fopen("$folder_name/".$file_name, 'w');
fwrite($file_handle, $front_side_svg);
fclose($file_handle);
Run Code Online (Sandbox Code Playgroud)

在服务器端我只是替换变量,所以我不知道如何在服务器上实现这一点.我愿意接受任何可以实现我预期产出的想法.

2op*_*pin 7

您可以使用PHP函数imageftfbox(应该启用GD lib).

它返回坐标数组[x0,y0,x1,y1,x2,y2,x3,y3].

基于它们,您可以确定它是否超出您的SVG元素位置,这是一个如何执行此操作的示例:

function cutStringToPix($str, $svgWidth, $fontSize = 14, $font='times_new_roman.ttf', $delimiter = '') 
  $font = './fonts/' .$font;
  $sWidth = $svgWidth;
  $newStr = $str;
  $words = $delimiter
     ? explode($delimiter, $str)
     : str_split($str);
  $wordsCnt = count($words);

  // Reduce your string until it fits
  for (;$sWidth >= $svgWidth && $wordsCnt; $wordsCnt--) {
    $newStr = implode(' ', array_slice($words, 0, $wordsCnt));
    $bbox = imagettfbbox($fontSize, 0, $font, $newStr);
    $sWidth = $bbox[2] - $bbox[0];
  };
  return $newStr;
}
// Now use your $newStr
Run Code Online (Sandbox Code Playgroud)

好吧,这是你评论的榜样

它使用TimesNewRoman字体,你需要为它找到TTF (比如这个...)并将它保存在服务器上的"fonts"目录中(相对于你想要存储'cutStringToPix'func的你的lib.php)为'times_new_roman .TTF"

然后你的SVG形成部分将是这样的:

//include 'cutStringPix' func

$message_string = array('{first_name}','{last_name}');
$replace_string = array('Fist Name of User','Last Name Of User');
$front_svg_url = $svg_url.$res_code[0]['front_side_svg_image'];
$front_raw_svg = file_get_contents($front_svg_url);
//so what we adding:
$replace_string = cutStringToPix($replace_string, 162, 13);

$front_side_svg = str_ireplace($message_string, $replace_string, $front_raw_svg);
$file_name = uniqid($prefix).".svg";
Run Code Online (Sandbox Code Playgroud)