Udostępnij za pośrednictwem


Moving and Bouncing Circle with HTML5 Canvas

 

This should work in ie9 and chrome.  However, if you use ie9, make sure you set the browser and document mode to IE9 standards.  There could be some refactor done on this code, but I wrote this in a few hours without any prior javascript or html5 experience:

test.html:

 

<html>

<head>

    <style type="text/css">  

      canvas { border: 1px solid black; }  

    </style>  

</head>

<body>

<script type="text/javascript" src="test.js"></script>

<button onclick="StartCircle()">startit!</button><br />

</body>

</html>

 

 

test.js:

var circle;

var path;

var canvas

var context

var keepgoing = true;

var maxwidth;

var maxheight;

var radius = 50;

var interval;

 

function StartCircle() {

    if (canvas == null) {

        canvas = document.createElement('canvas');

        document.getElementsByTagName('body')[0].appendChild(canvas);

    }

    maxwidth = Math.floor(Math.random() * 700 + 100);

    maxheight = Math.floor(Math.random() * 700 + 100);

 

    canvas.setAttribute("width", maxwidth);

    canvas.setAttribute("height", maxheight);

 

    context = canvas.getContext('2d');

 

    startwidth = Math.floor(Math.random() * (maxwidth - radius*2)) + radius;

    startheight = Math.floor(Math.random() * (maxheight - radius*2)) + radius;

 

    path = new Path(startwidth, startheight);

    circle = new Circle(startwidth, startheight, radius);

    if (interval != null)

        clearInterval(interval);

    interval  = setInterval(Draw, 1);

 

}

 

function BorderSwitch(x, y)

{

    var flipx = false;

    var flipy = false;

    if ((x+radius) == maxwidth || (x-radius) == 0)

        flipx = true;

    if ((y+radius) == maxheight || (y-radius) == 0)

        flipy = true;

 

    return new Flip(flipx, flipy);

}

 

function Flip(flipx, flipy)

{

    this.flipx = flipx;

    this.flipy = flipy;

}

 

function Path(x, y) {

    this.x = x;

    this.y = y;

    deltax = Math.floor(Math.random() * 2) == 0? -1: 1;

    deltay = Math.floor(Math.random() * 2) == 0 ? -1 : 1;

 

    this.GetNext = function () {

        var directionswitch = BorderSwitch(this.x, this.y);

        if (directionswitch.flipx == true)

            deltax *= -1;

        if (directionswitch.flipy == true)

            deltay *= -1;

 

        this.x += deltax;

        this.y += deltay;

 

    };

}

 

function Circle(x, y, radius) {

    this.x = x;

    this.y = y;

    this.radius = radius;

 

}

 

function Draw() {

    path.GetNext();

    circle.x = path.x;

    circle.y = path.y;

    context.clearRect(0, 0, maxwidth, maxheight);

    context.strokeStyle = "#000000";

    context.fillStyle = "#FFFF00";

    context.beginPath();

    context.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2, true);

    context.closePath();

    context.stroke();

    context.fill();

}