Kris Catalan
Kris Catalan

Reputation: 33

How to make my drawing move inside HTML5 canvas?

I have a HTML5 canvas and Javascript. How can I make it move like move it's arms and feet?

I tried Googling for some tutorials but failed.

Attached here is my image and my codes:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="canvascss.css">
</head>

<body>
    <div>
    <canvas id="canvas" width="400px" height="300px" >
        Your browser does not support HTML5 Canvas element
    </canvas>
    </div>

    <script>
    var canvas = document.getElementById("canvas");
    if (canvas.getContext("2d")) { // Check HTML5 canvas support
    context = canvas.getContext("2d"); // get Canvas Context object

    context.beginPath();
    context.fillStyle = "black"; // #ffe4c4
    context.arc(200, 50, 30, 0, Math.PI * 2, true); // draw circle for head
    context.fill();

    context.beginPath();
    context.strokeStyle = "black"; // color
    context.lineWidth = 3;
    context.arc(200, 50, 20, 0, Math.PI, false); // draw semicircle for smiling
    context.stroke();

    // eyes
    context.beginPath();
    context.fillStyle = "black"; // color
    context.arc(190, 45, 3, 0, Math.PI * 2, true); // draw left eye
    context.fill();
    context.arc(210, 45, 3, 0, Math.PI * 2, true); // draw right eye
    context.fill();

    // body
    context.beginPath();
    context.moveTo(200, 80);
    context.lineTo(200, 180);
    context.strokeStyle = "black";
    context.stroke();

    // arms
    context.beginPath();
    context.strokeStyle = "black"; // blue
    context.moveTo(200, 80);
    context.lineTo(150, 130);
    context.moveTo(200, 80);
    context.lineTo(250, 130);
    context.stroke();

    // legs
    context.beginPath();
    context.strokeStyle = "black";
    context.moveTo(200, 180);
    context.lineTo(150, 280);
    context.moveTo(200, 180);
    context.lineTo(250, 280);
    context.stroke();
}

</script>

</body>
</html>

Result:

enter image description here

Upvotes: 3

Views: 1794

Answers (1)

EnglishAdam
EnglishAdam

Reputation: 1390

From HTML5 Canvas Animation with requestAnimFrame:

To create an animation using HTML5 Canvas, we can use the requestAnimFrame shim which enables the browser to determine the optimal FPS for our animation. For each animation frame, we can update the elements on the canvas, clear the canvas, redraw the canvas, and then request another animation frame.

In short your point of departure is the following:

requestAnimationFrame

You will need a javascript function to CHANGE aspects of your starting image, and then to call that javascript code at regular intervals.

setInterval is another key word to google and learn from.

Upvotes: 1

Related Questions