如何使用圆弧平滑画布中绘制的圆的边缘?

时间:2014-02-13 18:27:37

标签: javascript html5 html5-canvas

我在使用圆弧绘制html5画布中的圆圈,但边缘粗糙且不平滑。我希望能让他们顺利。堆叠溢出需要我写更多,所以我的代码与文本比率更好

代码

(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||   window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
}());

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

createCircle(100, 150, '85', '675');
createCircle(300, 150, '70', '479');
createCircle(500, 150, '91', '715');
createCircle(700, 150, '58', '334');


function createCircle(x, y, temp, hash, callback) {
  var radius = 75;
  var endPercent = parseInt(temp, 10);
  var curPerc = 0;
  var counterClockwise = false;
  var circ = Math.PI * 2;
  var quart = Math.PI / 2;

  context.strokeStyle ='#006600';
  context.lineWidth = 10;
  context.lineCap = "round";
  var offset = quart;

function doText(context, x, y, temp, hash) {
    context.lineWidth = 10;  
    if(parseInt(temp, 10) > 90)
        context.fillStyle = '#ad2323';
    else if(parseInt(temp, 10) > 82)
        context.fillStyle = '#ffcc33';
    else
        context.fillStyle = '#006600';

    context.font = "28px sans-serif";
    context.fillText(temp + 'º', x - 20, y + 10);
    context.fillText(hash + 'KH/s', x - 50, y - 90);
}

function animate(current) {
    context.lineWidth = 10;
    if(curPerc > 89)
        context.strokeStyle = '#ad2323';
    else if(curPerc > 81)
        context.strokeStyle = '#ffcc33';

    context.beginPath();
    context.arc(x, y, radius, offset, ((circ) * current) + offset , false);
    context.stroke();
    context.closePath();      
    curPerc++;
    if (curPerc < endPercent) {
       requestAnimationFrame(function () {
            animate(curPerc / 100);
        });
    } 
    else {
        doText(context, x, y, temp, hash);
        if (callback) callback.call();
    }
 }
 animate();
}

JSFiddle = http://jsfiddle.net/uhVj6/712/

1 个答案:

答案 0 :(得分:8)

您正在多次绘制笔划,以便它们相互绘制。您需要清除旧弧形笔划所在的区域,然后绘制新的弧形笔划

context.clearRect(x - radius - context.lineWidth, 
                  y - radius - context.lineWidth, 
                  radius * 2 + (context.lineWidth*2), 
                  radius * 2 + (context.lineWidth*2));
context.beginPath();
context.arc(x, y, radius, offset, ((circ) * current) + offset , false);
context.stroke();
context.closePath();

JSFiddle