Square following a line
Demonstrates a square following a prescribed path
by wooozy
HTML
<div id="position"></div>
<canvas id="myCanvas" width="900" height="400"></canvas>
JavaScript
$('#myCanvas').click(function () {
});
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function drawRectangle(r, c) {
c.beginPath();
c.rect(r.x, r.y, r.width, r.height);
c.fillStyle = '#8ED6FF';
c.fill();
c.lineWidth = r.borderWidth;
c.strokeStyle = 'yellow';
c.stroke();
}
function drawBoard(c) {
c.beginPath();
c.moveTo(upperLeft.x, upperLeft.y + 5);
c.lineTo(upperRight.x + 5, upperRight.y + 5);
c.lineTo(lowerRight.x + 5, lowerRight.y + 5);
c.lineTo(lowerLeft.x + 5, lowerLeft.y + 5);
c.lineTo(upperLeft.x + 5, upperLeft.y + 5)
c.strokeStyle = 'black';
c.lineWidth = carWidth;
c.stroke();
}
function animate(r, canvas, context) {
// X motion
if (r.x >= upperRight.x && r.y <= upperRight.y) {
stepX = 0;
stepY = 1;
}
if (r.x >= lowerRight.x && r.y >= lowerRight.y) {
stepX = -1;
stepY = 0;
}
if (r.x <= lowerLeft.x && r.y >= lowerLeft.y) {
stepX = 0;
stepY = -1;
}
if (r.x <= upperLeft.x && r.y <= upperLeft.y) {
stepX = 1;
stepY = 0;
}
r.x += stepX;
r.y += stepY;
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
drawBoard(context);
drawRectangle(r, context);
// request new frame
requestAnimFrame(function () {
// This is where animate gets called
$('#position').html("x:" + r.x + " y:" + r.y);
animate(r, canvas, context);
});
}
var startX = 50;
var startY = 50;
var stopX = 250;
var stopY = 250;
var carWidth = 10;
var carHeight = 10;
var stepX = 1;
var stepY = 0;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var...