S
S
sazhyk2021-07-30 13:37:39
JavaScript
sazhyk, 2021-07-30 13:37:39

How does jQuery .clone() work under the hood?

You need to save the html page as an image. The page is not initially static. Its content is generated. The goal is to take a screenshot of the image preview page. All examples are taken from the web.

Page piece
<input type="button" id="btn_convert" value="Screenshot">
        <input type="file" id="addImages" multiple="">
        <ul id="uploadImagesList">
            <li class="item template">
                <span class="img-wrap">
                    <img src="" alt="">
                </span>
                <span class="delete-link" title="Удалить">Удалить</span>
            </li>
        </ul>
        <div class="clear"></div>
        <div id="previewImg">
            <p>Preview</p>
        </div>


Script that generates previews for files
jQuery(document).ready(function ($) {

    var maxFileSize = 8 * 1024 * 1024; // (байт) Максимальный размер файла (8мб)
    var queue = {};
    var imagesList = $('#uploadImagesList');

    var itemPreviewTemplate = imagesList.find('.item.template').clone(true);
    itemPreviewTemplate.removeClass('template');
    imagesList.find('.item.template').remove();
    $('#addImages').on('change', function () {
        var files = this.files;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            if ( !file.type.match(/image\/(jpeg|jpg|png|gif)/) ) {
                alert( 'Фотография должна быть в формате jpg, png или gif' );
                continue;
            }
            if ( file.size > maxFileSize ) {
                alert( 'Размер фотографии не должен превышать 8 Мб' );
                continue;
            }
            preview(files[i]);
        }
        this.value = '';
    });

    // Создание превью
    function preview(file) {
        var reader = new FileReader();
        reader.addEventListener('load', function(event) {
            var img = document.createElement('img');
            var itemPreview = itemPreviewTemplate.clone(true);
            itemPreview.find('.img-wrap img').attr('src', event.target.result);
            itemPreview.data('id', file.name);
            imagesList.append(itemPreview);
            queue[file.name] = file;
        });
        reader.readAsDataURL(file);
    }

    // Удаление фотографий
    imagesList.on('click', '.delete-link', function () {
        var item = $(this).closest('.item'),
            id = item.data('id');
        delete queue[id];
        item.remove();
    });

});


After that, I need to save the page as an image. Before that, the screen is inserted into the block for checking on the page. Then it loads. I use html2canvas for this.
Screenshot
document.getElementById("btn_convert").addEventListener("click", function() {
html2canvas(document.getElementById("uploadImagesList"),
    {
        allowTaint: true,
        useCORS: true
    }).then(function (canvas) {
        var anchorTag = document.createElement("a");
        document.body.appendChild(anchorTag);
        document.getElementById("previewImg").appendChild(canvas);
        anchorTag.download = "filename.jpg";
        anchorTag.href = canvas.toDataURL();
        anchorTag.target = '_blank';
        anchorTag.click();
    });
});

Actually the problem is that the preview is done, and the canvas is then empty on the page.

Here's what happens
<div id="previewImg">
    <p>Preview</p>
    <canvas width="976" height="0"></canvas>
</div>


I am not strong in JS. Here I have a suspicion that I do not quite understand how .clone () from JQuery works correctly under the hood. It seemed to me that it was impossible to add elements created dynamically to the canvas. Can someone explain what I'm doing wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question