I work with uploading photos, trying to display thumbnails of these photos. To resize photos I use canvas . The problem is that canvas draws smaller photos, although for a photo I set the same dimensions as the canvas itself.
The problem, it seems to me, lies in the very drawing ctx.drawImage(img, 0, 0, width, height); but I don’t know how to win it.
The purpose of these gestures is to facilitate the work of the browser, since users (They are the aunts) will load the pictures directly from the camera, that is, the situation when 500 pieces of pictures with a size of 5k pixels are displayed is a common thing.
//Готовим шаблон let template = document.getElementById('file-template'); let cTemplate = Handlebars.compile(template.innerHTML); let input = document.getElementById('file-input'); input.onchange = function() { let container = document.getElementById('photos'); let files = this.files; //Перебираем файлы в мультиинпуте for(let i in files) { if(!files.hasOwnProperty(i)) continue; let file = files[i]; if (!file.type.match(/image.*/)) continue; let reader = new FileReader(); //Когда картинка прочиталась reader.onload = function(e) { let img = new Image(); img.src = e.target.result; //Вставляем из шаблона container.insertAdjacentHTML( 'beforeend', cTemplate() ); let canvas = container.querySelector('.file:last-of-type .canvas'); let ctx = canvas.getContext('2d'); let height = 100; //Высота превьюх 100 let width = img.width * height / img.height; //Посчитаем их длину canvas.style['width'] = width + 'px'; //Канвас хотим длиной с картинку ctx.drawImage(img, 0, 0, width, height); //Тут почему-то неправильно отрабатывает }; reader.readAsDataURL(file); } }; #photos { display: flex; margin-top: 20px; } .file { position: relative; margin: 0 5px 5px 0; } .file-delete { position: absolute; top: 0; right: 0; background: #fff; width: 18px; color: #f00; text-align: center; text-decoration: none; } canvas { background: #ccc; width: 0px; height: 100px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js"></script> <input id="file-input" type="file" multiple="multiple"> <div id="photos"></div> <script id="file-template" type="text/x-handlebars-template"> <div class="file"> <a href='#' class="file-delete">×</a> <canvas class="canvas"></canvas> </div> </script>