HTML 5 canvas keydown event animation - javascript

So I'm fairly new to programming and I've been playing a bit around with HTML 5 and canvas. I've been trying to get a simple rectangle to move when pressing down a key, but I simply can't get i to work. I've followed this guide: http://www.homeandlearn.co.uk/JS/html5_canvas_keyboard_keys.html
Here's my code:
HTML:
CanvasTest
<link rel="stylesheet" href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/bootstrap.css">
<link rel="stylesheet" href="TestStyle.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="TestApp.js"></script>
</head>
<body>
<canvas id="canvas" width="400" height="500"></canvas>
</body>
</html>
JS:
var main = function (){
var canvas = document.getElementById("canvas");
canvas.addEventListener("keydown", doKeyDown, true);
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(0, 0, 255, 1)"
ctx.fillRect(20, 20, 20, 15);
var x = 30;
var y = 30;
function doKeyDown(key) {
alert (key.keyCode)
if (key.keyCode == 87) { //w
clearCanvas();
y = y - 10;
ctx.fillStyle = "rgba(0, 0, 255, 1)"
ctx.fillRect(x, y, 20, 15)
}
if (key.keyCode == 83) { //s
clearCanvas();
y = y + 10;
ctx.fillStyle = "rgba(0, 0, 255, 1)"
ctx.fillRect(x, y, 20, 15)
}
if (key.keyCode == 65) { //a
clearCanvas();
y = x - 10;
ctx.fillStyle = "rgba(0, 0, 255, 1)"
ctx.fillRect(x, y, 20, 15)
}
if (key.keyCode == 68) { //d
clearCanvas();
y = x + 10;
ctx.fillStyle = "rgba(0, 0, 255, 1)"
ctx.fillRect(x, y, 20, 15)
}
}
function clearCanvas() {
canvas.width = canvas.width;
}
};
$(document).ready(main);
CSS:
canvas {
border: 1px solid #ddd;
margin-left: auto;
margin-right: auto;
margin-bottom: 50px;
margin-top: 50px;
padding-left: 0;
padding-right: 0;
padding-bottom: 0;
padding-top: 0;
display: block;
}
When I load it up I get the canvas and the rectangle is displayed, yet I am not able to move the rectangle with WASD

I have put comments to show you the changes in place.
I don't feel i need to explain much with very few changes but I have added comments to point them out.
Additional: Auto focus & focus outline remove (See comments in source code)
var main = function (){
var canvas = document.getElementById("canvas");
canvas.addEventListener("keydown", doKeyDown, true);
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(0, 0, 255,.5)";
//_______________________________^ .5 = 50%/Half Alpha
ctx.fillRect(20, 20, 20, 15);
//----- Optional auto focus -------
//If you want the page to focus on your canva
canvas.focus();
var x = 30;
var y = 30;
function doKeyDown(key) {
if (key.keyCode == 87) { //w
clearCanvas();
y = y - 10;
ctx.fillStyle = "rgba(0, 0, 255,.5)";
ctx.fillRect(x, y, 20, 15);
}
if (key.keyCode == 83) { //s
clearCanvas();
y = y + 10;
ctx.fillStyle = "rgba(0, 0, 255,.5)";
ctx.fillRect(x, y, 20, 15);
}
if (key.keyCode == 65) { //a
clearCanvas();
x = x - 10; //Move Left -10 from x-axis
ctx.fillStyle = "rgba(0, 0, 255,.5)";
ctx.fillRect(x, y, 20, 15);
}
if (key.keyCode == 68) { //d
clearCanvas();
x = x + 10; //Move right +10 from x-axis
ctx.fillStyle = "rgba(0, 0, 255,.5)";
//__________________________________^ Close ;
ctx.fillRect(x, y, 20, 15);
}
}
function clearCanvas() {
canvas.width = canvas.width;
}
};
$(document).ready(main);
canvas {
border: 1px solid #ddd;
margin-left: auto;
margin-right: auto;
margin-bottom: 50px;
margin-top: 50px;
padding-left: 0;
padding-right: 0;
padding-bottom: 0;
padding-top: 0;
display: block;
/*------ Remove outline on focus*/
/*outline: 0;*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="400" height="400" tabindex="0"></canvas>
<!--_________________________________________^^^^^ Missing tabindex -->
I hope this helps. Happy Coding!

On second evaluation, I have found some more error
I made a crude moving example (most important changes in code)
http://jsfiddle.net/zfbukakc/2/
canvas = document.getElementById("canvas");
window.addEventListener("keydown", doKeyDown, true);
ctx = canvas.getContext("2d");
x = 30;
y = 30;
The main issue seems to be variable scope check http://www.w3schools.com/js/js_scope.asp
Will explain further in detail when I got some time later

Related

js canvas object movement animation using pythagorean theorem

I am trying to make an object move to click position, like in rpgs like diablo or modern moba games, i needed to find a way to animate to click coordinates and i have found a method that uses pythagorean theorem, i understood and custimized the code to a certain degree, but there is a bug where the ball keeps bouncing in the very end of animation. I know this happens because of the "moves" variable and the loop, but can't understand exactly why.
here's the function that draws the object
function drawPlayer() {
//
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(player.x, player.y, 12, 0, Math.PI*2);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();
//Calculate variables
let dx = player.newx - player.x;
let dy = player.newy - player.y;
let distance = Math.sqrt(dx*dx + dy*dy);
let moves = distance/player.speed;
let xunits = (player.newx - player.x)/moves;
let yunits = (player.newy - player.y)/moves;
if (moves > 0 ) {
moves--;
player.x += xunits;
player.y += yunits;
console.log(moves);
}
}
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.addEventListener('click', e => {
setClickCoords(e);
drawPlayer();
})
canvas.width = 300;
canvas.height = 300;
const player = {
x: 0,
y: 0,
newx: 0,
newy: 0,
speed: 1,
radius: 15,
}
function drawPlayer() {
//Draw
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(player.x, player.y, 12, 0, Math.PI * 2);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();
//Calculate variables
let dx = player.newx - player.x;
let dy = player.newy - player.y;
let distance = Math.sqrt(dx * dx + dy * dy);
let moves = distance / player.speed;
let xunits = (player.newx - player.x) / moves;
let yunits = (player.newy - player.y) / moves;
console.log(moves);
if (moves > 0) {
moves--;
player.x += xunits;
player.y += yunits;
console.log(moves);
}
}
function setClickCoords(e) {
player.newx = e.offsetX;
player.newy = e.offsetY;
document.getElementById('oldcoords').innerHTML = "old Coords " + player.x + " " + player.y;
document.getElementById('newcoords').innerHTML = "new Coords " + player.newx + " " + player.newy;
}
function gameLoop() {
window.setTimeout(gameLoop, 24);
drawPlayer()
}
gameLoop();
body {
background: black;
display: flex;
flex-direction: column;
}
#canvas1 {
border: 3px solid white;
top: 50%;
left: 50%;
position: absolute;
width: 300px;
height: 300px;
transform: translate(-50%, -50%);
}
#oldcoords,
#newcoords {
color: white;
font-size: 18px;
}
<span id="oldcoords"></span>
<span id="newcoords"></span>
<canvas id="canvas1"> </canvas>
Check if moves is between 0 and 1. If it's between, move the ball to the desired position. Currently, the ball goes too far in the direction and has to return in the next animation.
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.addEventListener('click', e => {
setClickCoords(e);
drawPlayer();
})
canvas.width = 300;
canvas.height = 300;
const player = {
x: 0,
y: 0,
newx: 0,
newy: 0,
speed: 1,
radius: 15,
}
function drawPlayer() {
//Draw
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(player.x, player.y, 12, 0, Math.PI * 2);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();
//Calculate variables
let dx = player.newx - player.x;
let dy = player.newy - player.y;
let distance = Math.sqrt(dx * dx + dy * dy);
let moves = distance / player.speed;
console.log(moves);
if (moves > 1) {
let xunits = (player.newx - player.x) / moves;
let yunits = (player.newy - player.y) / moves;
moves--;
player.x += xunits;
player.y += yunits;
console.log(moves);
} else if (moves > 0) {
moves = 0;
player.x = player.newx;
player.y = player.newy;
console.log(moves);
}
}
function setClickCoords(e) {
player.newx = e.offsetX;
player.newy = e.offsetY;
document.getElementById('oldcoords').innerHTML = "old Coords " + player.x + " " + player.y;
document.getElementById('newcoords').innerHTML = "new Coords " + player.newx + " " + player.newy;
}
function gameLoop() {
window.setTimeout(gameLoop, 24);
drawPlayer()
}
gameLoop();
body {
background: black;
display: flex;
flex-direction: column;
}
#canvas1 {
border: 3px solid white;
top: 50%;
left: 50%;
position: absolute;
width: 300px;
height: 300px;
transform: translate(-50%, -50%);
}
#oldcoords,
#newcoords {
color: white;
font-size: 18px;
}
<span id="oldcoords"></span>
<span id="newcoords"></span>
<canvas id="canvas1"> </canvas>

Why is the bullet not drawn when the background is?

I am trying to make bullet objects for my HTML game, but they won't get drawn, even though the background (which is drawn the same way before the bullets) works.
<!DOCTYPE html>
<html>
<head>
<title>
Shooter
</title>
<style>
body{
background-color: blue;
}
canvas{
position: absolute;
top: 50px;
left: 50px;
}
h1{
color: yellow;
position: absolute;
top: 0px;
left: 50px;
}
p{
color: red;
position: absolute;
top: 450px;
left: 50px;
}
</style>
</head>
<body onkeydown='getKeyAndMove(event)'>
<h1>
Shooter
</h1>
<canvas width='800' height='400' id='myCanvas'></canvas>
<p>
Use Up and Down to move, Space to shoot. Don't get hit!
</p>
<script>
var start = null;
var playery = 0;
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var radius = 1;
var bullets = [null];
var enemies = new Array(null);
function fire(playery, bullets, enemies){
if (bullets[0] === null){
console.log(9)
bullets[0] = {
x:0,
y:playery,
length:50,
height:25,
update: function(enemies){
bullets[0].x += 5;
var maxCount = enemies.length;
/*for (i=0; i<maxCount; i++){
var enemy = enemies[i];
if (enemy.x <= bullets[0].x + bullets[0].length){
if (enemy.x + enemy.length >= bullets[0].x){
if (enemy.y + enemy.height >= bullets[0].y){
if (enemy.y <= bullets[0].y + bulets[0].height){
enemies[i] = null;
bullets[0] = null;
}
}
}
}
}*/
if (bullets[0].x >= 800){
bullets[0] = null;
return;
}
}
};
}
};
function getKeyAndMove(e){
var key_code=e.which||e.keyCode;
switch(key_code){
case 38:
playery -= 5
break;
case 40:
playery += 5
break;
case 32:
console.log(32)
fire(playery, bullets, enemies);
break;
}
};
function step(timestamp){
if (!start) start = timestamp;
var progress = timestamp - start;
ctx.fillStyle = 'white'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = 'rgb(0, 0, 0)'
ctx.fillRect(1, 1, canvas.width - 2, canvas.height - 2)
var i=0;
var j=0;
for (i=0; i < 800; i++){
for (j=0; j < 400; j++){
if (Math.random() > 0.9999) {
ctx.beginPath();
ctx.arc(i, j, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'white';
ctx.fill();
ctx.lineWidth = 0;
ctx.strokeStyle = '#FFFFFF';
ctx.stroke();
ctx.closePath();
}
}
}
if (bullets[0] != null){
bullets[0].update(enemies)
console.log(0)
if(bullets[0] != null){
ctx.fillStyle = '#DD0000'
ctx.fillRect(bullets[0].x, bullets[0].y, bullets[0].width, bullets[0].height)
}
}
window.requestAnimationFrame(step)
}
window.requestAnimationFrame(step)
</script>
</body>
</html>
The console shows no errors when I run the code. I have set it to log every frame that there is a bullet, and the log is showing up, the bullet just never appears.
What am I doing wrong?
I accidentally typed width instead of length in line 126. The problem is solved.

clearRect isnt clearing canvas

im developing a game as a coding exercise and ive come across a bug that i cant find when ever i press the selected button it does not remove the shape and redraw anotheer one it for some reason just keeps the shape on the page and draws a new shae i need it to delete the old shape and redraw a new shape this is how the game should work
enter code here
window.addEventListener("load", function() {
function clear(ctx, width, height) {
}
function drawRandomShape(width, height) {
//ctx.clearRect(0,0, canvas.width, canvas.height)
canvas.style.backgroundColor = 'white';
// var num = Math.floor(Math.random() * 10)
var number = 30;
var countdown = setInterval(function(){
timerSpan.innerHTML = number--;
//console.log(number)
if(number == 0 - 1){
clearInterval(countdown);
}
},1000);
function randomShape(){
var randomNum = Math.floor(Math.random() * 10);
//ctx.clearRect(0,0, canvas.width, canvas.height)
// if(number > 0){
if(randomNum >= 0 && randomNum <= 2){
// ctx.clearRect(0, 0, canvas.width, canvas.height);
var triangle = ctx.beginPath();
triangle += ctx.moveTo(0, 0);
triangle += ctx.lineTo(90, 90);
triangle += ctx.lineTo(0, 90);
triangle += ctx.closePath();
triangle += ctx.fillStyle = "red";
triangle += ctx.fill();
document.addEventListener('keyup', function shape(e){
if(e.keyCode == 37){
triangle += ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
document.removeEventListener('keyup', shape);
randomShape();
}
});
}else if(randomNum > 2 && randomNum <= 4){
// ctx.clearRect(0,0, canvas.width, canvas.height);
var blackTriangle = ctx.fillStyle = "black";
blackTriangle += ctx.beginPath();
blackTriangle += ctx.moveTo(0,0);
blackTriangle += ctx.lineTo(90, 90);
blackTriangle += ctx.lineTo(0, 90);
blackTriangle += ctx.fill();
document.addEventListener('keyup', function shape(e){
if(e.keyCode == 38){
blackTriangle += ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
document.removeEventListener('keyup', shape);
randomShape();
}
});
}else if(randomNum >= 4 && randomNum <= 6){
//ctx.clearRect(0, 0, canvas.width, canvas.height);
var redSquare = ctx.fillStyle = 'black';
redSquare += ctx.rect(200, 100, 90, 90)
redSquare += ctx.fill();
document.addEventListener('keyup', function shape(e){
if(e.keyCode == 39){
redSquare += ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
randomShape()
}
});
}else if(randomNum > 6 && randomNum < 10){
//ctx.clearRect(0,0, canvas.width, canvas.height);
var whiteSquare = ctx.rect(50,70,90,90);
whiteSquare += ctx.fillStyle = 'red';
whiteSquare += ctx.fill();
document.addEventListener('keyup', function shape(e) {
if(e.keyCode == 40){
whiteSquare += ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
document.removeEventListener('keyup', shape);
randomShape();
}
});
}
console.log(randomNum)
//};
}
randomShape();
}
//}, 1000);
function drawGameStartText(width, height ,score) {
width = 170;
height = 350;
ctx.fillStyle = 'White';
ctx.font = '30px Verdana'
ctx.fillText('Press space bar to start a new game' , width , height);
}
function restartGame(ctx, width, height){
}
var canvas = document.getElementById("shapes-game"),
height = canvas.scrollHeight,
width = canvas.scrollWidth,
gameOn = false,
expectedKey = undefined,
ctx = canvas.getContext('2d'),
// white triangle = up, red square = down,
// red triangle = left, white square = right
expectedKeysMap = {white0: 38, red1: 40, red0: 37, white1: 39};
timerSpan = document.getElementById("time-remaining");
scoreSpan = document.getElementById("score-val"),
seconds = 3;
// intervalId;
document.addEventListener("keyup", function(e) {
e.preventDefault();
if(e.keyCode == 32){
drawRandomShape();
}
});
drawGameStartText()
})
body {
padding-bottom: 50px;
}
#shapes-game {
border: 4px solid grey;
background-color: black;
}
.canvas-container {
padding: 10px;
}
.canvas-container, #shapes-game {
height: 750px;
width: 800px;
}
.scores {
padding: 10px;
text-align: center;
}
.legend {
padding-top: 15px;
}
.legend-contents {
text-align: left;
padding-left: 30px;
}
.triangle-bottomleft-red {
width: 0;
height: 0;
border-bottom: 50px solid red;
border-right: 50px solid transparent;
}
.triangle-bottomleft-black {
width: 0;
height: 0;
border-bottom: 54px solid black;
border-right: 58px solid transparent;
}
.triangle-inner-white {
position: relative;
top: 2px;
left: 2px;
width: 0;
height: 0;
border-bottom: 50px solid white;
border-right: 50px solid transparent;
}
.triangle-left {
width: 0;
height: 0;
border-top: 23px solid transparent;
border-bottom: 23px solid transparent;
border-right: 23px solid red;
}
.inner-triangle {
position: relative;
top: -20px;
left: 2px;
width: 0;
height: 0;
border-top: 20px solid transparent;
border-bottom: 20px solid transparent;
border-right: 20px solid blue;
}
.red-square {
width: 50px;
height: 50px;
background-color: red;
}
.white-square {
width: 50px;
height: 50px;
background-color: white;
border-style: solid;
border-width: 1px;
}
<!DOCTYPE html>
<html>
<head>
<title>Shapes!!</title>
<link rel="stylesheet" type="text/css" href="vendor/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="vendor/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="vendor/bootstrap.min.js"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="container">
<div class="col-xs-10 canvas-container">
<canvas id="shapes-game" height="750" width="800"></canvas>
</div>
<div class="col-xs-2 scores">
<h1>Score</h1>
<h3><span id="score-val">0</span></h3>
<h1>Timer</h1>
<h3><span id="time-remaining">30</span></h3>
<div class="legend">
<h1>Legend</h1>
<div class="legend-contents">
<div class="triangle-bottomleft-red">
</div>
<h4>Left</h4>
<div class="white-square">
</div>
<h4>Right</h4>
<div class="triangle-bottomleft-black">
<div class="triangle-inner-white"></div>
</div>
<h4>Up</h4>
<div class="red-square">
</div>
<h4>Down</h4>
</div>
</div>
</div>
</div>
</body>
</html>
There are a zillion things wrong with your code.
First of why are you doing
var blackTriangle = ctx.fillStyle = "black";
blackTriangle += ctx.beginPath();
As it does absolutely nothing.
Create one key handler and handle everything in that rather than
document.addEventListener('keyup', function shape(e){
if(e.keyCode == 39){
redSquare += ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
randomShape()
}
});
You are just creating a pile of key handlers.
If you want to track shapes you are drawing create an array for each shape
const shapes = {
whiteSquares : [],
redSquares : [],
whiteTriangle : [],
redTriangle: [],
};
then when you add the shape add it to the appropriate array
if(randomNum <= 2){
ctx.beginPath();
ctx.lineTo(0, 0);
ctx.lineTo(90, 90);
ctx.lineTo(0, 90);
ctx.closePath();
ctx.fillStyle = "red";
ctx.fill();
shapes.redTriangle.push([0,0]); // store the top left of the triangle
}
Then you can clear it in the key handler
var gameStarted = false;
const keyNames = {
space : 32,
left : 37;
up : 38,
right : 39,
down : 40,
}
// only one key handler needed.
document.addEventListener('keyup', e => {
if(gameStarted === false && e.keyCode === keyNames.space) {
gameStarted = true;
drawRandomShape();
}else if(e.keyCode === keyNames.left) {
if(shapes.redTriangle.length > 0){
var pos = shapes.redTriangle.shift(); // remove the bottom item in the array
ctx.clearRect(pos[0],pos[1],90,90); // clear that position
randomShape(); // create anothe shape.
}
}else if(e.keyCode === keyNames.right) {
if(shapes.whiteSquares.length > 0){
// same as above
}
}else if(e.keyCode === keyNames.up) {
if(shapes.whiteTriangle.length > 0){
// same as above
}
}else if(e.keyCode === keyNames.down) {
if(shapes.redSquares.length > 0){
// same as above
}
}
}
Dont over complicate conditional statements.
You have
var randomNum = Math.floor(Math.random() * 10);
if(randomNum >= 0 && randomNum <= 2){
// do stuff
}else if(randomNum > 2 && randomNum <= 4){
// do stuff
}else if(randomNum >= 4 && randomNum <= 6){
// do stuff
}else if(randomNum > 6 && randomNum < 10){
// do stuff
}
is the same as
var randomNum = Math.floor(Math.random() * 10);
if (randomNum <= 2) {
// do stuff
} else if(randomNum <= 4) {
// do stuff
} else if(randomNum <= 6) {
// do stuff
} else {
// do stuff
}

Is there a way to make this move in a circle in stead of a square?

I'm just playing around with canvas and I'm trying to make it move in a circle instead of a sqaure, is that possible? If it is, how?
This is what I have so far and I don't know how to make it move in a circle.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>derp</title>
</head>
<body>
<canvas id="canvas" width="800" height="500" style="border:1px solid #d3d3d3;"></canvas>
<script type="text/javascript" language="JavaScript">
var height = 500;
var width = 800;
var radius = 100;
var x = 100;
var y = 100;
var xass = 0;
function draw(){
if(x == 100 && y == 100){
xass = 0
}
if(x == 700 && y == 100){
xass = 1
}
if(x == 700 && y == 400){
xass = 2
}
if(x == 100 && y == 400){
xass = 3
}
if( xass == 0){
x++
}
else if(xass == 1){
y++
}
else if(xass == 2){
x--
}
else if(xass == 3){
y--
}
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 800, 500);
ctx.beginPath();
ctx.moveTo(400,250);
ctx.lineTo(x,y);
ctx.stroke();
ctx.beginPath();
ctx.arc(x,y,5,0,2*Math.PI);
ctx.stroke();
ctx.fill();
ctx.beginPath();
ctx.arc(400,250,15,0,2*Math.PI);
ctx.stroke();
}
</script>
<style>
canvas {
margin-left: auto;
margin-right: auto;
display: block;
}
</style>
</body>
</html>
See this https://jsfiddle.net/kup3qe5c/2/ i just made use of a circle function (math)
var height = 500;
var width = 800;
var radius = 150;
var x,y;
var step = 2*Math.PI/20;
var h = width/2;
var k = height/2;
var theta = 0;
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
function draw(){
theta += step
x = h + radius*Math.cos(theta);
y = k - radius*Math.sin(theta);
ctx.clearRect(0, 0, 800, 500);
ctx.beginPath();
ctx.moveTo(400,250);
ctx.lineTo(x,y);
ctx.stroke();
ctx.beginPath();
ctx.arc(x,y,5,0,2*Math.PI);
ctx.stroke();
ctx.fill();
ctx.beginPath();
ctx.arc(400,250,15,0,2*Math.PI);
ctx.stroke();
}
setInterval(draw,100);
// Create a rectangle shaped path with its top left point at
// {x: 75, y: 75} and a size of {width: 75, height: 75}
var path = new Path.Rectangle({
point: [75, 75],
size: [75, 75],
strokeColor: 'black'
});
function onFrame(event) {
// Each frame, rotate the path by 3 degrees:
path.rotate(3);
}
will this help

Can't figure out where to draw image in Javascript code

I am having issues trying to place an image as an object for an "asteroid avoidance" game. I was able to get the game itself to work based on what was written in my book "Foundation: HTML5 Canvas for Games and Entertainment". I want to go one step beyond what was written in the book. I want to replace the triangle shaped ship with that of an image. However, I am unable to figure out where to put the code for this.draw. My professor showed us a way to do it. When I try to implement it into my code it doesn't want to work properly. May I ask for some advice on how to place the image as the ship?
Here is my working code from the book, before I made any this.draw edits:(http://jsbin.com/tukejopofo/1/)
$(document).ready(function() {
var canvas = $("#gameCanvas");
var context = canvas.get(0).getContext("2d");
//canvas dimensions
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
var playGame;
var asteroids;
var numAsteroids;
var player;
var score;
var scoreTimeout;
var arrowUp = 38;
var arrowRight = 39;
var arrowDown = 40;
var arrowLeft = 37;
//game UI
var ui = $("#gameUI");
var uiIntro = $("#gameIntro");
var uiStats = $("#gameStats");
var uiComplete = $("#gameComplete");
var uiPlay = $("#gamePlay");
var uiReset = $(".gameReset");
var uiScore = $(".gameScore");
var soundBackground = $("#gameSoundBackground").get(0);
var soundThrust = $("#gameSoundThrust").get(0);
var soundDeath = $("#gameSoundDeath").get(0);
var Asteroid = function(x, y, radius, vX) {
this.x = x;
this.y = y;
this.radius = radius;
this.vX = vX;
};
var Player = function(x, y) {
this.x = x;
this.y = y;
this.width = 24;
this.height = 24;
this.halfWidth = this.width / 2;
this.halfHeight = this.height / 2;
this.flameLength1 = 20;
this.flameLength2 = 20;
this.vX = 0;
this.vY = 0;
this.moveRight = false;
this.moveUp = false;
this.moveDown = false;
this.moveLeft = false;
};
//Reset and start the game
function startGame() {
//Reset game stats
uiScore.html("0");
uiStats.show();
//set up initial game settings
playGame = false;
asteroids = new Array();
numAsteroids = 10;
score = 0;
player = new Player(150, canvasHeight / 2, 50, 50);
for (var i = 0; i < numAsteroids; i++) {
var radius = 5 + (Math.random() * 10);
var x = canvasWidth + radius + Math.floor(Math.random() * canvasWidth);
var y = Math.floor(Math.random() * canvasHeight);
var vX = -5 - (Math.random() * 5);
asteroids.push(new Asteroid(x, y, radius, vX));
};
$(window).keydown(function(e) {
var keyCode = e.keyCode;
if (!playGame) {
playGame = true;
soundBackground.currentTime = 0;
soundBackground.play();
animate();
timer();
};
if (keyCode == arrowRight) {
player.moveRight = true;
if (soundThrust.paused) {
soundThrust.currentTime = 0;
soundThrust.play();
}
} else if (keyCode == arrowLeft) {
player.moveLeft = true;
} else if (keyCode == arrowUp) {
player.moveUp = true;
} else if (keyCode == arrowDown) {
player.moveDown = true;
}
});
$(window).keyup(function(e) {
var keyCode = e.keyCode;
if (!playGame) {
playGame = true;
animate();
};
if (keyCode == arrowRight) {
player.moveRight = false;
if (keyCode == arrowRight) {
player.moveRight = false;
soundThrust.pause();
}
} else if (keyCode == arrowUp) {
player.moveUp = false;
} else if (keyCode == arrowDown) {
player.moveDown = false;
} else if (keyCode == arrowLeft) {
player.moveLeft = false;
}
});
//start the animation loop
animate();
};
//initialize the game environment
function init() {
uiStats.hide();
uiComplete.hide();
uiPlay.click(function(e) {
e.preventDefault();
uiIntro.hide();
startGame();
});
uiReset.click(function(e) {
e.preventDefault();
uiComplete.hide();
$(window).unbind("keyup");
$(window).unbind("keydown");
soundThrust.pause();
soundBackground.pause();
clearTimeout(scoreTimeout);
startGame();
});
};
function timer() {
if (playGame) {
scoreTimeout = setTimeout(function() {
uiScore.html(++score);
if (score % 5 == 0) {
numAsteroids += 5;
}
timer();
}, 1000);
};
};
//Animation loop that does all the fun stuff
function animate() {
//Clear
context.clearRect(0, 0, canvasWidth, canvasHeight);
var asteroidsLength = asteroids.length;
for (var i = 0; i < asteroidsLength; i++) {
var tmpAsteroid = asteroids[i];
tmpAsteroid.x += tmpAsteroid.vX;
if (tmpAsteroid.x + tmpAsteroid.radius < 0) { //creates bounderies to prevent player from leaving the canvas
tmpAsteroid.radius = 5 + (Math.random() * 10);
tmpAsteroid.x = canvasWidth + tmpAsteroid.radius;
tmpAsteroid.y = Math.floor(Math.random() * canvasHeight);
tmpAsteroid.vX = -5 - (Math.random() * 5);
}
var dX = player.x - tmpAsteroid.x;
var dY = player.y - tmpAsteroid.y;
var distance = Math.sqrt((dX * dX) + (dY * dY));
if (distance < player.halfWidth + tmpAsteroid.radius) { //checks for collision
soundThrust.pause()
soundDeath.currentTime = 0;
soundDeath.play();
//Game over
playGame = false;
clearTimeout(scoreTimeout);
uiStats.hide();
uiComplete.show();
soundBackground.pause();
$(window).unbind("keyup"); //unbinds keys to stop player movement at the end of the game
$(window).unbind("keydown");
};
context.fillStyle = "rgb(255, 255, 255)";
context.beginPath();
context.arc(tmpAsteroid.x, tmpAsteroid.y, tmpAsteroid.radius, 0, Math.PI * 2, true);
context.fill();
};
player.vX = 0;
player.vY = 0;
if (player.moveRight) {
player.vX = 3;
};
if (player.moveLeft) {
player.vX = -3;
};
if (player.moveUp) {
player.vY = -3;
};
if (player.moveDown) {
player.vY = 3;
};
player.x += player.vX;
player.y += player.vY;
if (player.x - player.halfWidth < 20) {
player.x = 20 + player.halfWidth;
} else if (player.x + player.halfWidth > canvasWidth - 20) {
player.x = canvasWidth - 20 - player.halfWidth;
}
if (player.y - player.halfHeight < 20) {
player.y = 20 + player.halfHeight;
} else if (player.y + player.halfHeight > canvasHeight - 20) {
player.y = canvasHeight - 20 - player.halfHeight;
}
if (player.moveRight) {
context.save();
context.translate(player.x - player.halfWidth, player.y);
if (player.flameLength1 == 20) {
player.flameLength1 = 15;
(player.flameLength2 == 20)
player.flameLength2 = 15;
} else {
player.flameLength1 = 20;
player.flameLength2 = 20;
};
context.fillStyle = "orange";
context.beginPath();
context.moveTo(0, -12);
context.lineTo(-player.flameLength1, -7);
context.lineTo(0, -5);
context.closePath();
context.fill();
context.fillStyle = "orange";
context.beginPath();
context.moveTo(0, 12);
context.lineTo(-player.flameLength2, 7);
context.lineTo(0, 5);
context.closePath();
context.fill();
context.restore();
};
//draw ship
context.fillStyle = "rgb(255, 0, 0)";
context.beginPath();
context.moveTo(player.x + player.halfWidth, player.y);
context.lineTo(player.x - player.halfWidth, player.y - player.halfHeight);
context.lineTo(player.x - player.halfWidth, player.y + player.halfHeight);
context.closePath();
context.fill();
while (asteroids.length < numAsteroids) { //adds asteroids as the difficulty increases
var radius = 5 + (Math.random() * 10)
var x = Math.floor(Math.random() * canvasWidth) + canvasWidth + radius;
var y = Math.floor(Math.random() * canvasHeight);
var vX = -5 - (Math.random() * 5);
asteroids.push(new Asteroid(x, y, radius, vX));
}
if (playGame) {
//run the animation loop again in 33 milliseconds
setTimeout(animate, 24);
};
};
init();
});
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
width: 100%;
}
canvas {
display: block;
}
body {
background: #000;
color: #fff;
font-family: Verdana, Arial, sans-serif;
font-size: 18px;
}
h1 {
font-size: 30px;
}
h6 {
font-size: 15px;
}
p {
margin: 0 20px;
}
a {
color: #fff;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a.button {
background: #185da8;
border-radius: 5px;
display: block;
font-size: 30px;
margin: 40px 0 0 350px;
padding: 10px;
width: 200px;
text-align: center;
}
a.button:hover {
background: #2488f5;
color: #fff;
text-decoration: none;
}
#game {
height: 600px;
left: 50%;
margin: -250px 0 0 -500px;
position: relative;
top: 50%;
width: 980px;
}
#gameCanvas {
background: #001022;
border: 5px solid green;
background-image: url(../images/space.jpg);
background-position: center top;
background-repeat: no-repeat;
background-size: cover;
}
#gameUI {
height: 600px;
position: absolute;
width: 980px;
}
#gameIntro,
#gameComplete {
background: rgba(0, 0, 0, 0.5);
margin: 100px 0 0 10px;
padding: 40px 0;
text-align: center;
}
#gameStats {
font-size: 14px;
margin: 20px 0;
}
#gameStats .gameReset {
margin: 20px 20px 0 0;
position: absolute;
right: 0;
top: 0;
}
<body>
<div id="game">
<div id="gameUI">
<div id="gameIntro">
<h1>Debris Fields of Spiral Galaxy</h1>
<h6>A <i>Galaxy Smuggler's Run</i> Game</h6>
<hr>
<p>You are Captain Amadaeus delivering goods to a dependent planet on the other side of a debris field</p>
<p>Click <i>"Play"</i> and then press any key to start.</p>
<p><a id="gamePlay" class="button" href="">Play!</a>
</p>
</div>
<div id="gameStats">
<p><b>Time: </b><span class="gameScore"></span> seconds</p>
<p><a class="gameReset" href="">Reset</a>
</p>
</div>
<div id="gameComplete">
<h1>Game Over!</h1>
<p>You survived for <span class="gameScore"></span> seconds.</p>
<p>Would you like to give it another go?</p>
<p><a class="gameReset button" href="">Play Again?</a>
</p>
</div>
</div>
<canvas id="gameCanvas" width="980" height="600">
</canvas>
<audio id="gameSoundBackground" loop>
<source src="sounds/background.ogg">
<source src="sounds/background.mp3">
</audio>
<audio id="gameSoundThrust" loop>
<source src="sounds/thrust.ogg">
<source src="sounds/thrust.mp3">
</audio>
<audio id="gameSoundDeath">
<source src="sounds/death.ogg">
<source src="sounds/death.mp3">
</audio>
</div>
</body>
and here is my Professor's code for drawing an image:(http://jsbin.com/rapayufafe/1/)
// JS file for the ship
function Ship() {
this.x = 100;
this.y = 100;
this.color = "yellow";
this.fillStyle = "white";
this.vx = 0;
this.vy = 0;
this.ax = 1;
this.ay = 1;
//function "move" that will add velocity to the position of the ship
this.move = function() {
this.x += this.vx;
this.y += this.vy;
}//end move function
//draw the ship
this.draw=function () {
//ship var
var imageObj = new Image();
imageObj.src = "images/ship.png";
//save the current state of the canvas
context.save();
//moving the point of origin (0,0) to the ships x and y coordinates
context.translate(this.x,this.y);
context.lineStyle = this.color;
context.fillStyle = this.fillStyle;
/*context.beginPath();
context.moveTo(25,0);
context.lineTo(-25,25)
context.lineTo(-25,-25)*/
//draw ship
context.drawImage(imageObj,-25,-25,50,50);
context.closePath();
context.stroke();
context.fill();
context.restore();
}//end of draw ship
}//end ship function
/*var asteroidsLength = asteroids.length;
for (var i = 0; i < asteroidsLength; i++) {
var tmpAsteroid = asteroids[i];
context.fillStyle = "gray";
context.beginPath();
context.arc(tmpAsteroid.x, tmpAsteroid.y, tmpAsteroid.radius, 0, Math.PI*2, true);
context.closePath();
context.fill();
};*/
As you can see in your starting code, you have a section looking like this:
//draw ship
context.fillStyle = "rgb(255, 0, 0)";
context.beginPath();
context.moveTo(player.x + player.halfWidth, player.y);
context.lineTo(player.x - player.halfWidth, player.y - player.halfHeight);
context.lineTo(player.x - player.halfWidth, player.y + player.halfHeight);
context.closePath();
context.fill();
Just replace that code with the code for drawing an image.
var imageObj = new Image();
imageObj.src = "images/ship.png";
context.drawImage(imageObj,player.x,player.y);
Although, I'd recommend declaring the imageObj and setting the source at the top of your code where you declare the rest of your variables so that you don't load the image every time you want to draw the ship.

Categories