Chụp hình thẻ DIV hoặc thẻ HTML bất kỳ với HTML2CANVAS
Đoạn code PHP ví dụ cách sử dụng html2canvas để chụp hình thẻ div với id là capture:
<!DOCTYPE html> <html lang="en"> <head> <title>Capture HTML tag</title> <?php $width = 100; $height = 'auto'; $s = 60; $fontfile = __DIR__ . '/font.ttf'; $actual_link = ( empty( $_SERVER['HTTPS'] ) ? 'http' : 'https' ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $base_url = dirname( $actual_link ); $fonturl = $base_url . '/' . basename( $fontfile ); $font_name = 'Agenda'; $x = 50; $y = 150; $t = 'Agenda Fantasy Halloween Font'; $color = '#000'; $bg = 'transparent'; $css = "@font-face{font-family:'$font_name';src:url('$fonturl') format('truetype')}"; ?> <style> body { margin: 0; font-family: '<?php echo $font_name; ?>'; } h1, h2, h3, h4, h5, h6 { margin: 0; } h6 { font-size: 18px; margin-bottom: 10px; } body * { box-sizing: border-box; } <?php echo $css; ?> </style> </head> <body> <?php if ( is_numeric( $width ) ) { if ( $width == 100 ) { $width .= '%'; } else { $width .= 'px'; } } if ( is_numeric( $height ) ) { $height .= 'px'; } $style = sprintf( 'font-size: %s; padding: %s; width: %s; height: %s; background-color: %s', $s . 'px', $x . 'px ' . $y . 'px', $width, $height, 'transparent' ); ?> <div id="capture" style="<?php echo $style; ?>"> <h6> <em>Example by <span style="font-family: Tahoma;">ldcuong.com</span></em> </h6> <h2 style="font-family: '<?php echo $font_name; ?>';" title="Normal font text"><?php echo $t; ?></h2> </div> <script src="html2canvas.min.js"></script> <script> if ("function" === typeof html2canvas) { html2canvas(document.querySelector("#capture"), { allowTaint: true, useCORS: true, backgroundColor: null, removeContainer: true }).then(canvas => { document.body.appendChild(canvas); const imageURL = canvas.toDataURL("image/png"); // Create a temporary link element const link = document.createElement("a"), img = document.createElement("img"); link.href = imageURL; img.src = link.href; link.download = "captured_image.png"; link.title = "Download image"; img.alt = link.title; link.appendChild(img); // Simulate a click on the link to trigger the download document.body.appendChild(link); }); } </script> </body> </html>
Bên dưới là hình ảnh kết quả của đoạn code bên trên:


Lại Đình Cường
Tôi làm quen và phát triển WordPress từ năm 2008, cho đến nay thì đã có hơn 13 năm kinh nghiệm, thật không thể tin được. Tôi có đam mê và dành nhiều thời gian làm việc với WordPress mỗi ngày, hiện tại tôi đang phát triển giao diện và plugin cho WordPress.
Nếu bạn đang cần người làm trang web bằng WordPress? Hãy liên hệ với tôi ngay để được tư vấn nhé.
Không có bình luận.
Bạn có thể trở thành người đầu tiên để lại bình luận.