Compression for true size compression
In the code
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title> </head> <body> <input ID ="fileInput" type="file"> <input ID ="textInput" Type ="text" placeholder=" placeholder "> <button id=" BTN "> </button> <br><br> <img id="img1" SRC ="" Alt =""> <! <img id="img2" SRC ="" Alt =""> <script> // get dom const fileInput = document.getelementById ('fileInput'); const textInput = document.getElementById('textInput'); const img1 = document.getElementById('img1'); const img2 = document.getElementById('img2'); const btn = document.getElementById('btn'); Const rea = new FileReader(); // Create canvas const c = document.createElement('canvas'); c.style.display = 'none'; document.body.appendChild(c); const ctx = c.getContext("2d"); Rea. onload = function (e) {img1.src = e.target.result; } fileInput.onchange = function (e) { rea.readAsDataURL(e.target.files[0]); } function doSubmit() {if (fileinput.files.length <= 0) {alert(' please select the image first '); return; } let ratio = Number(textInput.value); If (thewire < = 0 | | thewire > 4) {alert (' please enter a number greater than zero is less than 4 '); return; } let width = img1.width * ratio; let height = img1.height * ratio; c.width = width c.height = height; ctx.drawImage(img1, 0, 0, width, height); let src = c.toDataURL('image/png'); img2.src = src; Console. log(' compressed image SRC ', SRC); } btn.onclick = doSubmit; textInput.onkeypress = function (e) { let code = e.keyCode || e.which || e.charCode; if (code == 13) { doSubmit(); } } </script> </body> </html>Copy the code
Pay attention to the point
1. The SRC of the img file that needs to be drawn is a path import or a web address. If the image path is from a different source than the current page path, the canvas will report an error because of canvas contamination (the same origin policy of the browser). Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.