/** * 把圖片處理成圓形,如果不是正方形就按最小邊一半為半徑處理 * @param {object} imgObj 圖片(img)對象 * @param {number} imgType 設置生成圖片的大小:0設置生成的圖片大小是以圖片設置的css大小為准,1設置生成的圖片大小是以圖片分辨率為准,默認值為0 * @return {string} return base64 png圖片字符串 */ function circle_image_v2(img, imgType) { var type = imgType || 0; var radius, diameter, canvas, ctx, natural; if (type) { if (img.naturalWidth > img.naturalHeight) { radius = img.naturalHeight / 2; } else { radius = img.naturalWidth / 2; } } else { if (img.width > img.height) { radius = img.height / 2; } else { radius = img.width / 2; } if (img.naturalWidth > img.naturalHeight) { natural = img.naturalHeight; } else { natural = img.naturalWidth; } } diameter = radius * 2; canvas = document.createElement('canvas'); if (!canvas.getContext) { // 判斷瀏覽器是否支持canvas,如果不支持在此處做相應的提示 console.log('您的瀏覽器版本過低,暫不支持。'); return false; } canvas.width = diameter; canvas.height = diameter; contex = canvas.getContext("2d"); contex.clearRect(0, 0, diameter, diameter); contex.save(); contex.beginPath(); contex.arc(radius, radius, radius, 0, Math.PI * 2, false); contex.clip(); if (type) { contex.drawImage(img, 0, 0, diameter, diameter, 0, 0, diameter, diameter); } else { contex.drawImage(img, 0, 0, natural, natural, 0, 0, diameter, diameter); } contex.restore(); return canvas.toDataURL('image/png'); }
傳入要處理的圖片對象,返回base64鏈接
//window.requestAnimationFrame 的兼容 if(!window.requestAnimationFrame){ window.requestAnimationFrame = ( window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRquestAniamtionFrame || window.oRequestAnimationFrame || function (callback){ return setTimeout(callback,Math.floor(1000/60)) } ) } 作者:犯迷糊的小羊 鏈接:https://www.jianshu.com/p/e70c9cfbdb38 來源:簡書 簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。
參考鏈接:https://blog.csdn.net/fxss5201/article/details/79691923
