1 回答
TA贡献1752条经验 获得超4个赞
您多次在其自身上重新绘制相同的弧线。为了渲染平滑的弧线,我们需要半透明像素(抗锯齿),在其他半透明像素上绘制半透明像素将使它们更加不透明。
所以这里的解决方案是清除所有内容并在每一帧重新绘制所有内容。
有几种方法可以做到这一点,但最简单的方法之一可能是每次都渲染完整的馅饼,并仅使用合成在其上设置蒙版动画:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = x - 40;
var stops = [
//[ begin, end , color ]
[ 0, 45, '#000' ],
[ 45, 65, '#ff0000' ],
[ 65, 100, '#002bff' ]
];
var current = 0;
animate();
function drawFullPie() {
stops.forEach( function( stop , i) {
var begin = (stop[0] / 100 ) * Math.PI * 2;
var end = (stop[1] / 100 ) * Math.PI * 2;
context.beginPath();
context.moveTo( x, y );
context.arc( x, y, radius, begin, end );
context.fillStyle = stop[2];
context.fill();
} );
}
function drawMask() {
var begin = 0;
var end = (current / 100) * Math.PI * 2;
// Keep whatever is currently painted to the canvas
// only where our next drawings will appear
context.globalCompositeOperation = 'destination-in';
context.beginPath();
context.moveTo( x, y );
context.arc( x, y, radius, begin, end );
context.fill();
// disable masking
context.globalCompositeOperation = 'source-over';
}
function animate() {
// clear at every frame
context.clearRect( 0, 0, canvas.width, canvas.height );
// draw the full pie
drawFullPie();
// mask it as needed
drawMask();
// until complete
if( current ++ < 100 ) {
// do it again
requestAnimationFrame( animate );
}
}
<canvas id="myCanvas" height="300" width="300"></canvas>
添加回答
举报