canvas绘制圆形裁剪图片

2024-02-21  本文已影响0人  wayne1125

1、效果图

裁剪后头像
头像原图

2、实现思路

首先通过arc绘制圆形区域块,再通过drawImage绘制图片,根据图片宽高不同适配剪切不同方向的内容,将图片定位到圆形中心位置

3、实现代码(以下实现头像为例)

<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
// 创建Image对象加载图片
const img = new Image();
// 解决资源跨域问题
img.crossOrigin = 'Anonymous';
// 竖向图
img.src =  "https://img.haomeiwen.com/i6793907/67b96e641ab4fc8d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"
// 图片加载
img.onload = () => {  
    // 设置canvas尺寸与图像相同,防止拉伸  
    const imageWidth = img.width
    const imageHeight = img.height
    // 头像圆心坐标值
    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)
    // 清空画布内容
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 开始绘制圆形裁剪区域
    ctx.beginPath();
    ctx.arc(roundX, roundY, radius, 0, 2 * Math.PI);
    ctx.fill()
    ctx.closePath();
    ctx.clip();
    // 将图片绘制到指定位置
    ctx.drawImage(img, roundImageX ,roundImageY , roundImageWidth, roundImageHeight);
    // 转成base64码,抽离单独组件时可以用到
    const screenshot = canvas.toDataURL('image/png',1);
    console.log('screenshot',screenshot); 
};  
</script>
上一篇 下一篇

猜你喜欢

热点阅读