裁剪出图像圈并设置为favicon

时间:2015-10-25 13:53:33

标签: javascript jquery html css favicon

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

我已经能够使用JQuery将图像设置为图标,但我似乎无法使其成为圆形(使用CSS的border-radius)......

请帮忙!

由于

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

1 个答案:

答案 0 :(得分:2)

以下是解决方案:

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