I am new to javascript. I am trying to draw a pacman that opens and closes its mouth passing a drawing function with arguments to a callback setInterval.
Althoug the question has been posed several times, the implementations did not work with me -- for instance setInterval( function() { funca(parms); }, delay ); or setInterval(funca, delay, parms);.
If I get it properly, I need a function to draw an object and another to clear the screen. Thus, I need to launch two functions in sequence.
How can I do that (properly)?
Thank you
Here is the code I wrote:
<!doctype html>
<html>
<head>
<title>PacMan</title>
<link rel="stylesheet" href="styles.css">
<script src="grid.js"></script>
<script src="pacman.js"></script>
</head>
<body>
<h1>Animated PacMan</h1>
<canvas id="grid" width="400" height="400"></canvas>
<script>
var context = document.getElementById("grid").getContext("2d");
context.strokeStyle = "white";
context.lineWidth = 1.5;
var x= 0, y = context.canvas.height/2;
var z = 0.8;
//draw_pacman(context, context.canvas.width/2, y, 100, z); ## this works ##
setInterval(draw_pacman, 1.0, context, context.canvas.width / 2, y, 100, update(z));
</script>
</body>
</html>
with pacman.js:
function draw_pacman(ctx, x_crd, y_crd, radius, mouth) {
angle = 0.2 * Math.PI * mouth;
ctx.save();
ctx.fillStyle = "yellow";
ctx.strokeStyle = "black";
ctx.lineWidth = 0.5;
ctx.beginPath();
ctx.arc(x_crd, y_crd, radius, angle, -angle);
ctx.lineTo(x_crd, y_crd);
ctx.closePath()
ctx.fill();
ctx.stroke();
ctx.restore();
}
function update(x) {
x += 1;
}
function frame(ctx) {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
draw(ctx);
update();
}