canvas繪制圓形裁剪圖片

1、效果圖

裁剪后頭像

頭像原圖

2、實現(xiàn)思路

首先通過arc繪制圓形區(qū)域塊,再通過drawImage繪制圖片,根據(jù)圖片寬高不同適配剪切不同方向的內(nèi)容,將圖片定位到圓形中心位置

3、實現(xiàn)代碼(以下實現(xiàn)頭像為例)

<canvas id="myCanvas" width="500" height="500" style="border:1px solid red;background: #e8e8e8" />
<script>
// 獲取Canvas元素
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 頭像半徑
const radius = 50
// 創(chuàng)建Image對象加載圖片
const img = new Image();
// 解決資源跨域問題
img.crossOrigin = 'Anonymous';
// 豎向圖
img.src =  "https://upload-images.jianshu.io/upload_images/6793907-67b96e641ab4fc8d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"
// 圖片加載
img.onload = () => {  
    // 設(shè)置canvas尺寸與圖像相同,防止拉伸  
    const imageWidth = img.width
    const imageHeight = img.height
    // 頭像圓心坐標(biāo)值
    const roundX = 100 
    const roundY = 120
    // 縱向剪切圖片
    let direction = 'column'
    // 圖片剪切前適配中心位置的寬高
    let roundImageWidth = 0
    let roundImageHeight = 0
    // 圖片剪切X、Y軸偏移量
    let roundImageX = 0
    let roundImageY = 0
    // 橫向剪切圖片
    if(imageWidth > imageHeight) {
        direction = 'row'
    }
    // 縱向圖片計算偏移量
    if(direction === 'column'){
        roundImageWidth = radius * 2
        roundImageHeight = roundImageWidth * imageHeight / imageWidth
        roundImageX = roundX - radius
        roundImageY = roundY - roundImageHeight / 2
    } else{
        // 橫向向圖片計算偏移量
        roundImageHeight = radius * 2
        roundImageWidth = roundImageHeight * imageWidth / imageHeight
        roundImageY = roundY - radius
        roundImageX = roundX - roundImageWidth / 2
    }
    console.log(img)
    // 清空畫布內(nèi)容
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 開始繪制圓形裁剪區(qū)域
    ctx.beginPath();
    ctx.arc(roundX, roundY, radius, 0, 2 * Math.PI);
    ctx.fill()
    ctx.closePath();
    ctx.clip();
    // 將圖片繪制到指定位置
    ctx.drawImage(img, roundImageX ,roundImageY , roundImageWidth, roundImageHeight);
    // 轉(zhuǎn)成base64碼,抽離單獨組件時可以用到
    const screenshot = canvas.toDataURL('image/png',1);
    console.log('screenshot',screenshot); 
};  
</script>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容