html5 canvas circle,html - HTML5 Canvas - Fill circle with image - Stack Overflow

The problem with the clip() method is that Chrome will render the borders non antialiased, as shown in this question.

One solution is to use globalCompositeOperation as shown in Daniel's answer:

//set-up - probably only needs to be done once

var scratchCanvas = document.createElement('canvas');

scratchCanvas.width = 100;

scratchCanvas.height = 100;

var scratchCtx = scratchCanvas.getContext('2d');

//drawing code

scratchCtx.clearRect(0, 0, scratchCanvas.width, scratchCanvas.height);

scratchCtx.globalCompositeOperation = 'source-over'; //default

//Do whatever drawing you want. In your case, draw your image.

scratchCtx.drawImage(imageToCrop, ...);

//As long as we can represent our clipping region as a single path,

//we can perform our clipping by using a non-default composite operation.

//You can think of destination-in as "write alpha". It will not touch

//the color channel of the canvas, but will replace the alpha channel.

//(Actually, it will multiply the already drawn alpha with the alpha

//currently being drawn - meaning that things look good where two anti-

//aliased pixels overlap.)

//

//If you can't represent the clipping region as a single path, you can

//always draw your clip shape into yet another scratch canvas.

scratchCtx.fillStyle = '#fff'; //color doesn't matter, but we want full opacity

scratchCtx.globalCompositeOperation = 'destination-in';

scratchCtx.beginPath();

scratchCtx.arc(50, 50, 50, 0, 2 * Math.PI, true);

scratchCtx.closePath();

scratchCtx.fill();

//Now that we have a nice, cropped image, we can draw it in our

//actual canvas. We can even draw it over top existing pixels, and

//everything will look great!

ctx.drawImage(scratchCanves, ...);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值