1公浪、效果圖
裁剪后頭像
頭像原圖
2鸥拧、實(shí)現(xiàn)思路
首先通過arc繪制圓形區(qū)域塊榨崩,再通過drawImage繪制圖片,根據(jù)圖片寬高不同適配剪切不同方向的內(nèi)容蜓耻,將圖片定位到圓形中心位置
3、實(shí)現(xiàn)代碼(以下實(shí)現(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對(duì)象加載圖片
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'
}
// 縱向圖片計(jì)算偏移量
if(direction === 'column'){
roundImageWidth = radius * 2
roundImageHeight = roundImageWidth * imageHeight / imageWidth
roundImageX = roundX - radius
roundImageY = roundY - roundImageHeight / 2
} else{
// 橫向向圖片計(jì)算偏移量
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碼,抽離單獨(dú)組件時(shí)可以用到
const screenshot = canvas.toDataURL('image/png',1);
console.log('screenshot',screenshot);
};
</script>