var isInc = true;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var counter = 0;
setInterval(function () {
context.beginPath();
context.moveTo(10 + counter, 10);
context.lineTo(40, 40);
context.lineWidth = 1;
context.closePath();
context.stroke();
console.log(counter);
if (counter == 50) isInc = false;
else if (counter == 0) isInc = true;
if (isInc) counter = counter + 10;
else counter = counter - 10;
}, 1000);

<canvas id="myCanvas" width="578" height="200"></canvas>
&#13;
我的要求是:
答案 0 :(得分:2)
var isInc = true;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var counter = 0;
setInterval(function() {
context.clearRect(0, 0, 578, 200);
context.beginPath();
context.moveTo(10 + counter, 10);
context.lineTo(40, 40);
context.lineWidth = 1;
context.closePath();
context.stroke();
console.log(counter);
if (counter == 50) {
isInc = false;
} else if (counter == 0) {
isInc = true;
}
counter = isInc ? counter + 10 : counter - 10;
}, 1000);
&#13;
<canvas id="myCanvas" width="578" height="200"></canvas>
&#13;
.clearRect()
是必需的。