Canvas Palette line drawing
by Jim_Y
HTML
<div id="container">
<canvas id="palette" width="400" height="400">Your browser does not support the HTML5 canvas tag.</canvas>
</div>
CSS
#container {
width: 500px;
height: 500px;
margin: auto;
}
#palette {
border: 1px solid #c3c3c3;
}
JavaScript
function Palette(canvas, context, game) {
this.game = game;
this.X = 100;
this.Y = 100;
this.self = canvas;
this.context = context;
}
Palette.prototype.leftArrowPressed = function () {
this.X = this.X - this.game.speed;
this.context.lineTo(this.X, this.Y);
this.context.stroke();
}
Palette.prototype.rightArrowPressed = function () {
this.X = this.X + this.game.speed;
this.context.lineTo(this.X, this.Y);
this.context.stroke();
}
Palette.prototype.topArrowPressed = function () {
this.Y = this.Y - this.game.speed;
this.context.lineTo(this.X, this.Y);
this.context.stroke();
}
Palette.prototype.bottomArrowPressed = function () {
this.Y = this.Y + this.game.speed;
this.context.lineTo(this.X, this.Y);
this.context.stroke();
}
function Game(speed) {
this.speed = speed;
}
$(document).ready(function () {
var game = new Game(5);
var canvas = document.getElementById("palette");
var palette = new Palette(canvas, canvas.getContext("2d"), game);
palette.context.moveTo(palette.X, palette.Y);
palette.context.lineWidth = 1;
palette.context.beginPath();
$(document).keydown(function (e) {
if (e.keyCode == 37) {
// leftArrowPressed
palette.leftArrowPressed();
} else if (e.keyCode == 38) {
// topArrowPressed
palette.topArrowPressed();
} else if (e.keyCode == 39) {
// rightArrowPressed
palette.rightArrowPressed();
} else if (e.keyCode == 40) {
// bottomArrowPressed
palette.bottomArrowPressed();
}
return false;
});
});