Making character animation effects in PHP is not as intuitive as using JavaScript or CSS, but with some functions of the GD library, such as imagefontwidth() , we can still achieve interesting dynamic character effects. This article will explain how to use the imagefontwidth() function to combine a loop to generate a frame sequence of characters "animation", and finally output it into a dynamic effect that simulates the animation.
imagefontwidth() is a function in the PHP GD library used to get the specified font width. Its purpose is to return the font width in pixels used by the imagestring() and imagestringup() functions. This function is especially suitable for us to control the exact position of characters on the image.
$font = 5;
$charWidth = imagefontwidth($font);
In this example, we set the font to 5 and use imagefontwidth() to get the width of each character.
Let's build a simple animation effect: a character moves from left to right. Each frame is an image, and the position of the characters is determined by the frame number. Use imagefontwidth() to accurately calculate the horizontal offset of characters in an image.
<?php
$font = 5;
$char = '*';
$frameCount = 20;
$imageWidth = 200;
$imageHeight = 40;
$charWidth = imagefontwidth($font);
// Dynamically generate multiple frames
for ($frame = 0; $frame < $frameCount; $frame++) {
$im = imagecreate($imageWidth, $imageHeight);
$bgColor = imagecolorallocate($im, 255, 255, 255);
$textColor = imagecolorallocate($im, 0, 0, 0);
// Calculate characters x coordinate
$x = ($charWidth * $frame) % $imageWidth;
$y = ($imageHeight - imagefontheight($font)) / 2;
imagestring($im, $font, $x, $y, $char, $textColor);
// Save the frame as PNG document
$filename = "frame_$frame.png";
imagepng($im, $filename);
imagedestroy($im);
}
?>
The above code will generate 20 PNG images after the script is run, and the * characters in each image are moved one character width to the right than the previous one.
Although PHP itself cannot directly generate GIF animations, we can use external tools such as ImageMagick to synthesize these frames into GIF animations:
convert -delay 10 -loop 0 frame_*.png animation.gif
Or use online tools, such as visiting https://m66.net/tool/gifmaker to upload these frames of images to synthesize animations.
To implement character movement back and forth, you can map $frame to a "round trip" sequence, for example:
$step = $frame % ($frameCount * 2);
$offset = $step < $frameCount ? $step : (2 * $frameCount - $step - 1);
$x = ($charWidth * $offset) % $imageWidth;
In this way, the characters will move back and forth in the image, further enhancing the fun of the animation.