简体   繁体   中英

Is clearing canvas [ 2D Context ] in HTML5 necessary for good performance?

I have a 2D canvas and drawing circle indefinitely one above the other.

Take this example : http://jsfiddle.net/umaar/fnMvf/

<html>
    <head>
        </head>

<body>
    <canvas id="canvas1" width="500" height="500"></canvas>
</body>
</html>

JavaScript :

var currentEndAngle = 0
var currentStartAngle = 0;
var currentColor = 'black';
var lineRadius = 75;
var lineWidth = 15;

setInterval(draw, 50);

function draw() {
    var can = document.getElementById('canvas1'); // GET LE CANVAS
    var canvas = document.getElementById("canvas1");
    var context = canvas.getContext("2d");
    var x = canvas.width / 2;
    var y = canvas.height / 2;
    var radius;
    var width;

    var startAngle = currentStartAngle * Math.PI;
    var endAngle = (currentEndAngle) * Math.PI;

    currentStartAngle = currentEndAngle - 0.01;
    currentEndAngle = currentEndAngle + 0.01;

    if (Math.floor(currentStartAngle / 2) % 2) {
      currentColor = "white";
      radius = lineRadius - 1;
      width = lineWidth + 3;
    } else {
      currentColor = "black";
      radius = lineRadius;
      width = lineWidth;
    }

    var counterClockwise = false;

    context.beginPath();
    context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
    context.lineWidth = width;
    context.lineCap = "round";
    // line color
    context.strokeStyle = currentColor;
    context.stroke();
}

Do I really need to clear canvas at some specific interval ?

How does canvas work in that case ? As it is '2D' context, does it still store previous data ? If yes, What should be approach to achieve smoothness for drawing circle keeping performance in mind ?

Canvas is a drawing surface. When you draw an element (eg call fill method), you are just changing the color of some pixels on the drawing surface. The canvas does not store any information about the element being drawn. In your example, there is no need to clear the canvas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM