【问题标题】:Crop circle out of image and set as favicon从图像中裁剪圆圈并设置为网站图标
【发布时间】:2016-01-24 15:35:49
【问题描述】:

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

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

请帮忙!

谢谢

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

【问题讨论】:

标签: javascript jquery html css favicon


【解决方案1】:

解决办法如下:

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" />

【讨论】:

  • OP 想要在渲染之前将图像裁剪成圆形。
  • 我刚刚更新了我的代码。 @JLRishe 根本不需要投票。您可以在投反对票之前发表评论并等待一个小时或其他时间。
  • @MoshFeu 您的原始答案错过了问题的重点,该问题在标题中陈述了一次,在问题中陈述了两次。所以我认为投反对票是值得的,但既然你已经解决了,我很乐意撤销我的投反对票。
  • @JLRishe 我专注于问题的第一部分,从第二部分开始我完全忘记了。这就是为什么我认为我们应该写一个评论并等待。无论如何,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 2020-04-16
  • 2012-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多