微信頭像截取是一個很常見的應(yīng)用場景,以下是一個使用HTML實現(xiàn)的微信頭像自動截取的代碼:
<div id="preview"></div> <input type="file" id="fileInput" /> <script> var imgSrc = ""; var imgWidth, imgHeight; var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); document.getElementById("fileInput").onchange = function(){ var file = this.files[0]; if(!/image\/\w+/.test(file.type)){ alert("請確保文件為圖像類型!"); return false; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(){ imgSrc = this.result; var img = new Image(); img.src = imgSrc; img.onload = function(){ imgWidth = this.width; imgHeight = this.height; var ratio = imgWidth/imgHeight; canvas.width = canvas.height = Math.min(imgWidth, imgHeight); var x = (imgWidth-canvas.width)/2; var y = (imgHeight-canvas.height)/2; ctx.drawImage(img, x, y, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height); document.getElementById("preview").style.backgroundImage = "url("+canvas.toDataURL()+")"; } } } </script>
代碼中包含了一個文件選擇框和一個預(yù)覽框。當(dāng)用戶選擇文件時,通過FileReader將圖片轉(zhuǎn)化為base64編碼的字符串,并讀取圖片的寬度和高度。將canvas的大小設(shè)置為寬度和高度的最小值,再根據(jù)原圖片的寬高比計算需要裁剪的位置和大小。將原圖片裁剪后繪制到canvas中,并將結(jié)果顯示在預(yù)覽框中。