裁剪圈出图像并设置为图标

Crop circle out of image and set as favicon

我希望能够从 API(使用 AJAX、JQuery)抓取图像并能够从中裁剪出一个圆圈(使其成为圆形) 并将其设置为该页面的图标。我该怎么做(最好在 JS/Jquery 中)?

我已经能够使用 JQuery 将图像设置为网站图标,但我似乎无法将其设为圆形(使用 CSS 的边框半径)。 .

请帮忙!

谢谢

仅供参考:我试过这个:$("head").append('<link rel="shortcut icon" href="URL" style="border-radius: 24px;">') 48x48 图像

解决方法如下:

document.querySelector('input').addEventListener('change', function(e){
  var input = this;
  var reader = new FileReader();

  reader.onload = function (e) {
    // Create an image from the file
    var img = document.createElement('img');
        img.src = e.target.result;
        
    // Create canvas to convert the image to base64
    var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
    
    var ctx = canvas.getContext('2d');
    
    roundedImage(ctx, 0, 0, canvas.width, canvas.height, 5);
    ctx.clip();
    
    // draw the image on the canvas (the user can't see it).
    ctx.drawImage(img, 0, 0);
    ctx.restore();
    
    document.body.appendChild(canvas);
    
    // set the link's attribute to replace the icon
    document.querySelector('#icon').setAttribute('href', canvas.toDataURL());
  };

  // Start read the image who uploaded
  reader.readAsDataURL(input.files[0]);
});

function roundedImage(ctx,x,y,width,height,radius){
  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.lineTo(x + width - radius, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  ctx.lineTo(x + width, y + height - radius);
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  ctx.lineTo(x + radius, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  ctx.lineTo(x, y + radius);
  ctx.quadraticCurveTo(x, y, x + radius, y);
  ctx.closePath();
}
<link id="icon" rel="icon" type="image/x-icon" />

<input type="file" />