私はHTML 5とJavaScriptを初めて使用しています。私は停止ボタンを押すまで私のキャンバスに自動的に行を移動する予定です。これまでは、行を連続的に移動する方法を示す例が見つかりました。私はこの例に停止ボタン機能を追加しようとしました。html5で連続して行を移動するには?
ただし、行は自動的に移動が停止しました。代わりに、私は停止を押すたびに少し動く。エラーを見つけるために、開発者のコンソールを確認しました。コンソールは、最大コールスタックサイズを超えていることを示しました。
さらに、ラインを上下に動かすことができる2つのボタンを予定していますか?はいの場合、関数を描画するために異なる点配列を渡す必要があります。たとえば、誰かが左にクリックした場合、x座標は固定されていますが、yが増えている新しい配列を渡すべきですか?
私は、次のコードをしている:あなたは
requestAnimFrame(draw(runAnimation));
draw(runAnimation)
を呼び出し、機能draw
を、実行している
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<button type="button" id="stop">Stop</button>
<button type="button" id="left">Left</button>
<button type="button" id="right">Right</button>
<canvas id="canvas" width="600" height="400"></canvas>
<script>
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (/* function */ callback, /* DOMElement */ element) {
window.setTimeout(callback, 1000/60);
};
})();
var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 200;
var points = [],
currentPoint = 1,
nextTime = new Date().getTime() + 500,
pace = 150;
// make some points
for (var i = 0; i < 50; i++) {
points.push({
x: i * (canvas.width/50),
y: 100
});
}
function draw(runAnimation) {
if (runAnimation.value) {
if (new Date().getTime() > nextTime) {
nextTime = new Date().getTime() + pace;
currentPoint++;
if (currentPoint > points.length) {
currentPoint = 0;
}
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
ctx.lineWidth = 2;
ctx.strokeStyle = '#2068A8';
ctx.fillStyle = '#2068A8';
for (var p = 1, plen = currentPoint; p < plen; p++) {
ctx.lineTo(points[p].x, points[p].y);
}
ctx.stroke();
requestAnimFrame(draw(runAnimation));
}
}
var stop = document.getElementById('stop');
var left = document.getElementById('left');
var right = document.getElementById('right');
/*
* define the runAnimation boolean as an obect
* so that it can be modified by reference
*/
var runAnimation = {
value: false
};
stop.addEventListener('click', function() {
runAnimation.value = !runAnimation.value;
if (runAnimation.value) {
requestAnimationFrame(draw(runAnimation));
}
});
left.addEventListener('click', function() {
});
right.addEventListener('click', function() {
});
</script>
</body>
</html>