This JavaScript program demonstrates how to draw a bouncing square on a canvas element.
<!DOCTYPE html>
<html>
<head>
<title>XoaX.net's Javascript</title>
<script type="text/javascript" src="BouncingSquare.js"></script>
</head>
<body onload="Initialize()">
<canvas id="idCanvas" width="640" height ="480" style="background-color: #F0F0F0;"></canvas>
</body>
</html>var gdX = 100;
var gdY = 100;
var gdDx = 1;
var gdDy = 1;
var qContext2D = null;
function AnimationLoop() {
Draw("gray");
setTimeout(AnimationLoop, 1);
}
function Initialize() {
var qCanvas = document.getElementById("idCanvas");
qContext2D = qCanvas.getContext("2d");
AnimationLoop();
}
function Draw(sColor) {
qContext2D.lineWidth = 10;
qContext2D.clearRect(0, 0, 640, 480);
var dWidth = 10.0;
qContext2D.fillStyle = "black";
qContext2D.fillRect(gdX, gdY, dWidth, dWidth);
//qContext2D.fillRect(1, 1, 638, 478);
if (gdDx > 0) {
if (gdX + dWidth == 639) {
gdDx = -1;
}
} else {
if (gdX == 0) {
gdDx = 1;
}
}
if (gdDy > 0) {
if (gdY + dWidth == 479) {
gdDy = -1;
}
} else {
if (gdY == 0) {
gdDy = 1;
}
}
gdX += gdDx;
gdY += gdDy;
}
© 20072025 XoaX.net LLC. All rights reserved.