canvas實現圓角圖片 (處理原圖是長方形或正方形)

 /** * 生成圖片的縮略圖 * @param {[type]} img 圖片(img)對象或地址 * @param {[type]} width 縮略圖寬 * @param {[type]} height 縮略圖高 * @return {[type]} return base64 png圖片字符串 */
        function thumb_image(img, width, height) { if (typeof img !== 'object') { var tem = new Image(); tem.src = img; tem.setAttribute("crossOrigin",'Anonymous') img = tem; } img.onload = function(e) { var _canv = document.createElement('canvas'); _canv.width = width; _canv.height = height; _canv.getContext("2d").drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height); return _canv.toDataURL(); } } yuan_image('./images/cover.png') /** * 把圖片處理成圓形,若是不是正方形就按最小邊一半爲半徑處理 * @param {[type]} img 圖片(img)對象或地址 * @return {[type]} return base64 png圖片字符串 */
        function yuan_image(img) { if (typeof img !== 'object') { var tem = new Image() tem.src = img tem.setAttribute("crossOrigin",'Anonymous') img = tem } var w, h, _canv, _contex, cli img.onload = function(e) { console.log(e) if (img.width > img.height) { w = img.height h = img.height } else { w = img.width h = img.width } _canv = document.createElement('canvas') _canv.width = w _canv.height = h _contex = _canv.getContext("2d") cli = { x: w / 2, y: h / 2, r: w / 2 } _contex.clearRect(0, 0, w, h) _contex.save() _contex.beginPath() _contex.arc(cli.x, cli.y, cli.r, 0, Math.PI * 2, false) _contex.clip() _contex.drawImage(img, 0, 0) console.log(_canv.toDataURL()) return _canv.toDataURL() } }
相關文章
相關標籤/搜索