Alert when the car hits the track in canvas - javascript

var car;
var front;
var back;
var img = new Image();
img.src = 'https://cdn4.iconfinder.com/data/icons/transportation-2-4/60/transportation-2-flat-036-racing-car-top-512.png';
function startGame() {
car = new move(12, 20, "red", 600, 300);
pg.start();
}
var pg = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 1200;
this.canvas.height = 600;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateframe, 20);
window.addEventListener('keydown', function(e) {
e.preventDefault();
pg.keys = (pg.keys || []);
pg.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function(e) {
pg.keys[e.keyCode] = (e.type == "keydown");
})
},
stop: function() {
clearInterval(this.interval);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function move(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.speed = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = pg.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.drawImage(img, this.width / -2, this.height / -2,20,40);
ctx.beginPath();
ctx.moveTo(this.width / -2, this.height / -2);
ctx.lineTo(this.width / -2, 30);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(this.width / -2, 30);
ctx.lineTo(13, (this.height / -2)+40);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(14, (this.height / -2)+40);
ctx.lineTo(14, this.height / -2);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(14, this.height / -2);
ctx.lineTo(this.width / -2, this.height / -2);
ctx.stroke();
ctx.restore();
ctx.beginPath();
ctx.moveTo(300, 150);
ctx.lineTo(600, 800);
ctx.stroke();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
function updateframe() {
pg.clear();
car.moveAngle = 0;
car.speed = 0;
if (pg.keys && pg.keys[37]) {
if (pg.keys && pg.keys[40]) {
car.moveAngle = 5;
}
if (pg.keys && pg.keys[38]) {
car.moveAngle = -5;
}
}
if (pg.keys && pg.keys[39]) {
if (pg.keys && pg.keys[40]) {
car.moveAngle = -5;
}
if (pg.keys && pg.keys[38]) {
car.moveAngle = 5;
}
}
if (pg.keys && pg.keys[38]) {
car.speed = 5;
}
if (pg.keys && pg.keys[40]) {
car.speed = -5;
}
car.newPos();
car.update();
}
startGame();
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
There is a car and a line, now i want to make an alert whenever the car get touched by the the line.
I know how to do this logically. like if i convert the car image in four lines (border) then use line intersection formula to get if there is a intersection but i am new to this canvas drawing and i cant figure how to get the border line equation of car.
update: i have made lines of border around the car, now i just need help with getting if these lines intersects with each other...
code is updated plz check it now...
one more thing, at this point there is only one line and i am going to add more lines in it... so i need a function to call it more often and get if the lines are intersecting with car border...
Note : use arrow keys to move car in snippet

Related

How to add external javascript in react app

I made a JavaScript particle animation and it works fine on a normal html website.
I tried implementing it into my react app using react helmet/useEffect but both didn't work and I don't know what's going on.
Here is my script:
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = 'absolute';
canvas.style.width = '100%';
canvas.style.height = '100%';
const container = document.querySelector('.particles');
container.appendChild(canvas);
let particleArray;
class Particle {
constructor(x, y, dirX, dirY, size, color) {
this.x = x;
this.y = y;
this.dirX = dirX;
this.dirY = dirY;
this.size = size;
this.color = color;
this.scale = .1;
this.counter = 0;
}
draw() {
var gradient = ctx.createRadialGradient(this.x, this.y, this.size / 8, this.x, this.y, this.size);
gradient.addColorStop(0, 'white');
gradient.addColorStop(1, 'white');
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2, false);
ctx.shadowColor = this.color;
ctx.shadowBlur = 10;
ctx.fillStyle = this.color;
ctx.fill();
}
update() {
if (this.x + this.size > canvas.width || this.x - this.size < 0) {
this.dirX = -this.dirX;
}
if (this.y + this.size > canvas.height || this.y - this.size < 0) {
this.dirY = -this.dirY;
}
this.size += this.scale;
this.counter += .1;
if (this.counter > 3) {
this.scale = -this.scale;
this.counter = 0;
}
this.x += this.dirX;
this.y += this.dirY;
this.draw();
}
}
function init() {
particleArray = [];
for (let i = 0; i < 25; i++) {
let size = Math.random() * 3;
let x = Math.random() * (innerWidth - size * 2);
let y = Math.random() * (innerHeight - size * 2);
let dirX = (Math.random() * .4) - .2;
let dirY = (Math.random() * .4) - .2;
let colors = ['#721240']
let color = colors[Math.floor(Math.random() * colors.length)];
particleArray.push(new Particle(x, y, dirX, dirY, size, color));
}
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, innerWidth, innerHeight);
for (let i = 0; i < particleArray.length; i++) {
particleArray[i].update();
}
}
init();
animate();
window.addEventListener('resize', () => {
canvas.width = innerWidth;
canvas.height = innerHeight;
init()
})
And here is how I tried to add it to my react app in App.js:
<div className="particles">
{useScript("./assets/particles.js")}
</div>
useScript is a react function using useEffect:
import { useEffect } from "react";
function useScript(url) {
useEffect(() => {
const script = document.createElement("script");
script.src = url;
script.async = false;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, [url]);
}
export default useScript;
Please help I'm stuck...
Instead of injecting the script, why don't you directly inject the code itself in useEffect. That's worked for me on multiple occassions
This is my proposed code. console.log() things like canvas and particleArray at multiple places to get it right
import { useEffect } from "react";
function useScript(url) {
useEffect(() => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = 'absolute';
canvas.style.width = '100%';
canvas.style.height = '100%';
const container = document.querySelector('.particles');
container.appendChild(canvas);
let particleArray;
class Particle {
constructor(x, y, dirX, dirY, size, color) {
this.x = x;
this.y = y;
this.dirX = dirX;
this.dirY = dirY;
this.size = size;
this.color = color;
this.scale = .1;
this.counter = 0;
}
draw() {
var gradient = ctx.createRadialGradient(this.x, this.y, this.size / 8, this.x, this.y, this.size);
gradient.addColorStop(0, 'white');
gradient.addColorStop(1, 'white');
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2, false);
ctx.shadowColor = this.color;
ctx.shadowBlur = 10;
ctx.fillStyle = this.color;
ctx.fill();
}
update() {
if (this.x + this.size > canvas.width || this.x - this.size < 0) {
this.dirX = -this.dirX;
}
if (this.y + this.size > canvas.height || this.y - this.size < 0) {
this.dirY = -this.dirY;
}
this.size += this.scale;
this.counter += .1;
if (this.counter > 3) {
this.scale = -this.scale;
this.counter = 0;
}
this.x += this.dirX;
this.y += this.dirY;
this.draw();
}
}
function init() {
particleArray = [];
for (let i = 0; i < 25; i++) {
let size = Math.random() * 3;
let x = Math.random() * (innerWidth - size * 2);
let y = Math.random() * (innerHeight - size * 2);
let dirX = (Math.random() * .4) - .2;
let dirY = (Math.random() * .4) - .2;
let colors = ['#721240']
let color = colors[Math.floor(Math.random() * colors.length)];
particleArray.push(new Particle(x, y, dirX, dirY, size, color));
}
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, innerWidth, innerHeight);
for (let i = 0; i < particleArray.length; i++) {
particleArray[i].update();
}
}
init();
animate();
window.addEventListener('resize', () => {
canvas.width = innerWidth;
canvas.height = innerHeight;
init()
})
return ()=>{
window.removeEventListener('resize', () => {
canvas.width = innerWidth;
canvas.height = innerHeight;
init()
})
}
}, [url]);
}
export default useScript;

connect a line to the car in canvas

var car;
var front;
var back;
var carpoint1;
var carpoint2;
var carpoint3;
var carpoint4;
var img = new Image();
img.src = 'https://cdn4.iconfinder.com/data/icons/transportation-2-4/60/transportation-2-flat-036-racing-car-top-512.png';
function startGame() {
car = new move(12, 20, "red", 600, 300);
pg.start();
}
var pg = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1200;
this.canvas.height = 600;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateframe, 20);
window.addEventListener('keydown', function (e) {
e.preventDefault();
pg.keys = (pg.keys || []);
pg.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
pg.keys[e.keyCode] = (e.type == "keydown");
})
},
stop : function() {
clearInterval(this.interval);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function move(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.speed = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = pg.context;
ctx.save();
getcarpoints(this.x, this.y, this.angle);
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.drawImage(img, this.width / -2, this.height / -2,20,40);
ctx.restore();
ctx.beginPath();
ctx.moveTo(300, 150);
ctx.lineTo(600, 800);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(300, 150);
ctx.lineTo(carpoint1[0], carpoint1[1]);
ctx.stroke();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
function getcarpoints(prex,prey,rotation)
{
carpoint1=[getrotatedx(prex,prey,rotation), getrotatedy(prex,prey,rotation)];
carpoint2=[carpoint1[0], carpoint1[1]+40];
carpoint3=[carpoint2[0]+20, carpoint2[1]+40];
carpoint4=[carpoint3[0]+20, carpoint3[1]];
// console.log(carpoint1[0]);
}
function getrotatedx(prex,prey,rotation)
{
piangle=Math.abs((rotation/ Math.PI * 180)%360);
newx=Math.cos(piangle)*prex+(-(Math.sin(piangle)*prey));
return newx;
}
function getrotatedy(prex,prey,rotation)
{
piangle=Math.abs((rotation/ Math.PI * 180)%360);
newy=Math.sin(piangle)*prex+(Math.cos(piangle)*prey);
return newy;
}
function updateframe() {
pg.clear();
car.moveAngle = 0;
car.speed = 0;
if (pg.keys && pg.keys[37]) { if (pg.keys && pg.keys[40]) {car.moveAngle= 5; } if (pg.keys && pg.keys[38]){car.moveAngle = -5; } }
if (pg.keys && pg.keys[39]) { if (pg.keys && pg.keys[40]) {car.moveAngle= -5; } if (pg.keys && pg.keys[38]){car.moveAngle = 5; } }
if (pg.keys && pg.keys[38]) {car.speed= 5; }
if (pg.keys && pg.keys[40]) {car.speed= -5; }
car.newPos();
car.update();
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script src="control.js"></script>
</body>
</html>
Here is my full code in snippet. I am trying to make a line from one fix point to the car... and this is the problem.
Now when is horizontal at any x point it works perfectly but the moment car turn the angle changes and it all messes up! you can see that when you turn the car (use arrow and left or right arrow at the same time) the line jumps.
Note: it is my project requirement to do it with 2d rotation matrix which means I can't make the line before i restore the canvas.
carpoint1,2,3,4 are the corners of car but right now I am just working with the carpoint1.
Do something so getrotatedx and getrotatedy always gives correct value that are car coordinates after matrix rotation.
Use ctx.lineTo(this.x, this.y); instead of ctx.lineTo(carpoint1[0], carpoint1[1]);
var car;
var front;
var back;
var carpoint1;
var carpoint2;
var carpoint3;
var carpoint4;
var img = new Image();
img.src = 'https://cdn4.iconfinder.com/data/icons/transportation-2-4/60/transportation-2-flat-036-racing-car-top-512.png';
function startGame() {
car = new move(12, 20, "red", 600, 300);
pg.start();
}
var pg = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1200;
this.canvas.height = 600;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateframe, 20);
window.addEventListener('keydown', function (e) {
e.preventDefault();
pg.keys = (pg.keys || []);
pg.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
pg.keys[e.keyCode] = (e.type == "keydown");
})
},
stop : function() {
clearInterval(this.interval);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function move(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.speed = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = pg.context;
ctx.save();
getcarpoints(this.x, this.y, this.angle);
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.drawImage(img, this.width / -2, this.height / -2,20,40);
ctx.restore();
ctx.beginPath();
ctx.moveTo(300, 150);//fixed point
ctx.lineTo(600, 800);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(300, 150);
ctx.lineTo(this.x, this.y);
ctx.stroke();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
function getcarpoints(prex,prey,rotation)
{
carpoint1=[getrotatedx(prex,prey,rotation), getrotatedy(prex,prey,rotation)];
carpoint2=[carpoint1[0], carpoint1[1]+40];
carpoint3=[carpoint2[0]+20, carpoint2[1]+40];
carpoint4=[carpoint3[0]+20, carpoint3[1]];
// console.log(carpoint1[0]);
}
function getrotatedx(prex,prey,rotation)
{
piangle=Math.abs((rotation/ Math.PI * 180)%360);
newx=Math.cos(piangle)*prex+(-(Math.sin(piangle)*prey));
return newx;
}
function getrotatedy(prex,prey,rotation)
{
piangle=Math.abs((rotation/ Math.PI * 180)%360);
newy=Math.sin(piangle)*prex+(Math.cos(piangle)*prey);
return newy;
}
function updateframe() {
pg.clear();
car.moveAngle = 0;
car.speed = 0;
if (pg.keys && pg.keys[37]) { if (pg.keys && pg.keys[40]) {car.moveAngle= 5; } if (pg.keys && pg.keys[38]){car.moveAngle = -5; } }
if (pg.keys && pg.keys[39]) { if (pg.keys && pg.keys[40]) {car.moveAngle= -5; } if (pg.keys && pg.keys[38]){car.moveAngle = 5; } }
if (pg.keys && pg.keys[38]) {car.speed= 5; }
if (pg.keys && pg.keys[40]) {car.speed= -5; }
car.newPos();
car.update();
}
startGame()
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}

Keep a circle inside other circle (Canvas)

I am making a game. I want the player to not go outside the circular game region. the player should not cross the red circular line. It should remain inside and could move along the boundary.
I have written a simple function for collision detection between circles. I have found a bug in it too. I am getting a console.log() message of outside even if I am inside the game area.
It's happening when the player is at [x < 0]. Help me out please.
var Game = (function(window) {
var canvas = document.getElementById("game"),
ctx = canvas.getContext("2d");
var SCREEN_WIDTH = window.innerWidth,
SCREEN_HEIGHT = window.innerHeight;
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
var ROCK = "rock",
PAPER = "paper",
SCISSOR = "scissor";
var BG_IMAGE = document.getElementById("bg");
// this is the game area Radius
var GAME_R = 500;
var offsetX = 0,
offsetY = 0;
var player;
// circle collision detection
function checkCollision(x1, y1, r1, x2, y2, r2) {
var x = x1-x2;
var y = y1-y2;
var d = Math.hypot(x, y);
return d < r1 + r2;
}
function start() {
player = new Entity();
addEventListener("mousemove", function(e) {
var angle = Math.atan2(e.clientY - SCREEN_HEIGHT/2, e.clientX - SCREEN_WIDTH/2);
player.setAngle(angle);
}, true);
animLoop();
}
function update() {
offsetX = player.x - SCREEN_WIDTH/2;
offsetY = player.y - SCREEN_HEIGHT/2;
player.update();
}
function draw() {
ctx.save();
ctx.translate(-offsetX, -offsetY);
// bg
ctx.fillStyle = ctx.createPattern(BG_IMAGE, "repeat");
ctx.fillRect(offsetX, offsetY, SCREEN_WIDTH, SCREEN_HEIGHT);
// game area border
ctx.beginPath();
ctx.arc(0, 0, GAME_R, 0, Math.PI * 2);
ctx.closePath();
ctx.lineWidth = 5;
ctx.strokeStyle = "red";
ctx.stroke();
// player
player.draw();
ctx.restore();
}
function gameLoop() {
update();
// here
if(checkCollision(player.x, player.y, player.x, 0, 0, GAME_R)) {
console.log("inside");
} else {
console.log("outside");
}
draw();
}
function animLoop() {
window.requestAnimationFrame(animLoop);
gameLoop();
}
// player
function Entity() {
var self = {
x: 0,
y: 0,
r: 50,
entityType: PAPER,
angle: 0,
speed: 5
}
self.setSpeed = function(speed) {
this.speed = speed;
}
self.setAngle = function(angle) {
this.angle = angle;
}
self.update = function() {
this.x += this.speed * Math.cos(this.angle);
this.y += this.speed * Math.sin(this.angle);
}
self.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "grey";
ctx.fill();
ctx.fillStyle = "#fff";
ctx.font = "30px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(this.entityType, this.x, this.y);
}
return self;
}
start();
})(window);
<canvas id="game"></canvas>
<div style="display: none;">
<img id="bg" src="https://i.imgur.com/9qjEwiz.png">
</div>
This will check if the inner Circle inside the outer
function checkCollision(cxInner, cyInner, rInner, cxOuter, cyOuter, rOuter) {
return Math.sqrt(Math.pow(cxInner-cxOuter, 2) + Math.pow(cyInner-cyOuter, 2)) < rOuter - rInner;
}
complete code:
var Game = (function(window) {
var canvas = document.getElementById("game"),
ctx = canvas.getContext("2d");
var SCREEN_WIDTH = window.innerWidth,
SCREEN_HEIGHT = window.innerHeight;
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
var ROCK = "rock",
PAPER = "paper",
SCISSOR = "scissor";
var BG_IMAGE = document.getElementById("bg");
// this is the game area Radius
var GAME_R = 500;
var offsetX = 0,
offsetY = 0;
var player;
// circle collision detection
function checkCollision(cxInner, cyInner, rInner, cxOuter, cyOuter, rOuter) {
return Math.sqrt(Math.pow(cxInner-cxOuter, 2) + Math.pow(cyInner-cyOuter, 2)) < rOuter - rInner;
}
function start() {
player = new Entity();
addEventListener("mousemove", function(e) {
var angle = Math.atan2(e.clientY - SCREEN_HEIGHT/2, e.clientX - SCREEN_WIDTH/2);
player.setAngle(angle);
}, true);
animLoop();
}
function update() {
offsetX = player.x - SCREEN_WIDTH/2;
offsetY = player.y - SCREEN_HEIGHT/2;
player.update();
}
function draw() {
ctx.save();
ctx.translate(-offsetX, -offsetY);
// bg
ctx.fillStyle = ctx.createPattern(BG_IMAGE, "repeat");
ctx.fillRect(offsetX, offsetY, SCREEN_WIDTH, SCREEN_HEIGHT);
// game area border
ctx.beginPath();
ctx.arc(0, 0, GAME_R, 0, Math.PI * 2);
ctx.closePath();
ctx.lineWidth = 5;
ctx.strokeStyle = "red";
ctx.stroke();
// player
player.draw();
ctx.restore();
}
function gameLoop() {
update();
// here
if(!checkCollision(player.x, player.y, player.r, 0, 0, GAME_R)) {
player.back();
}
draw();
}
function animLoop() {
window.requestAnimationFrame(animLoop);
gameLoop();
}
// player
function Entity() {
var self = {
x: 0,
y: 0,
r: 50,
entityType: PAPER,
angle: 0,
speed: 5
};
self.setSpeed = function(speed) {
this.speed = speed;
};
self.setAngle = function(angle) {
this.angle = angle;
};
self.update = function() {
this.x += this.speed * Math.cos(this.angle);
this.y += this.speed * Math.sin(this.angle);
};
self.back = function() {
this.x -= this.speed * Math.cos(this.angle);
this.y -= this.speed * Math.sin(this.angle);
};
self.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "grey";
ctx.fill();
ctx.fillStyle = "#fff";
ctx.font = "30px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(this.entityType, this.x, this.y);
};
return self;
}
start();
})(window);
<canvas id="game"></canvas>
<div style="display: none;">
<img id="bg" src="https://i.imgur.com/9qjEwiz.png">
</div>

Trouble Displaying Canvas in Basic HTML Canvas Game

I am trying to create a basic HTML game using the Canvas element, but I am having trouble with it. Unfortunately, I don't know where the error is in my code, so I have posted the entirety of the document I'm working on below.
My problem: The canvas is not displaying when I run the HTML document.
This code's based off of (as in it pretty much is) the Movement tutorial from w3schools for using the Canvas, available at https://www.w3schools.com/graphics/tryit.asp?filename=trygame_movement_keyboard, but when chaing variable names I must've broken something, because after looking at this for hours I can't figure out what I'm missing.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload = "initial()">
<script>
var playerOne;
function initial() {
playerOne = new canvasObject(30, 30, "red", 225, 225);
gameArea.start();
}
var gameArea = {
canvas : document.createElement("canvas");
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
e.preventDefault();
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
stop : function() {
clearInterval(this.interval);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function canvasObject(width, height, color, x, y, type)
{
this.type = type;
this.width = width;
this.height = height;
this.speed = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = gameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
function updateGameArea() {
gameArea.clear();
playerOne.moveAngle = 0;
playerOne.speed = 0;
if (gameArea.keys && gameArea.keys[37]) {
playerOne.moveAngle = -1;
}
if (gameArea.keys && gameArea.keys[39]) {
playerOne.moveAngle = 1;
}
if (gameArea.keys && gameArea.keys[38]) {
playerOne.speed= 1;
}
if (gameArea.keys && gameArea.keys[40]) {
playerOne.speed= -1;
}
playerOne.newPos();
playerOne.update();
}
</script>
</body>
</html>
gameArea is an object. Object properties are separated with ,, not ;. Hence, there is a syntax error after the definition of canvas.
var playerOne;
function initial() {
playerOne = new canvasObject(30, 30, "red", 225, 225);
gameArea.start();
}
var gameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
e.preventDefault();
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
stop : function() {
clearInterval(this.interval);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function canvasObject(width, height, color, x, y, type)
{
this.type = type;
this.width = width;
this.height = height;
this.speed = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = gameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
function updateGameArea() {
gameArea.clear();
playerOne.moveAngle = 0;
playerOne.speed = 0;
if (gameArea.keys && gameArea.keys[37]) {
playerOne.moveAngle = -1;
}
if (gameArea.keys && gameArea.keys[39]) {
playerOne.moveAngle = 1;
}
if (gameArea.keys && gameArea.keys[38]) {
playerOne.speed= 1;
}
if (gameArea.keys && gameArea.keys[40]) {
playerOne.speed= -1;
}
playerOne.newPos();
playerOne.update();
}
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
<body onload = "initial()">
You have a syntax error:
var gameArea = {
canvas : document.createElement("canvas");
...
}
You've used ; instead of ,

I have taken an image and made it into my gamepiece put on a canvas, but won't rotate properly

I have taken an image and made it into my gamepiece put on a canvas, but I cannot get it to rotate properly. I apologize if my code is not very organized just got a little bit hurried. The problem will lie in the component function. Thank you for your help!
var myGamePiece;
function startGame() {
myGamePiece = new component(40, 40, "character.png", 300, 300, "image");
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas")
, start: function () {
this.canvas.width = 640;
this.canvas.height = 480;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
e.preventDefault();
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
}
, stop: function () {
clearInterval(this.interval);
}
, clear: function () {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.width = width;
this.height = height;
this.speed = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.update = function () {
ctx = myGameArea.context;
if (type == "image") {
ctx.save();
ctx.rotate(this.angle);
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
ctx.restore();
} else {
ctx.save();
ctx.translate(this.x, this.y);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
}
}
this.newPos = function () {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
this.hitBottom = function () {
var bottom = myGameArea.canvas.height - 20;
if (this.y > bottom) {
this.y = this.y - 2.5;
}
}
this.hitTop = function () {
if (this.y < 20) {
this.y = this.y + 2.5;
}
}
this.hitLeft = function () {
if (this.x < 20) {
this.x = this.x + 2.5;
}
}
this.hitRight = function () {
var side = myGameArea.canvas.width - 20;
if (this.x > side) {
this.x = this.x - 2.5;
}
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.moveAngle = 0;
myGamePiece.speed = 0;
if (myGameArea.keys && myGameArea.keys[37]) {
myGamePiece.moveAngle = -2.5;
}
if (myGameArea.keys && myGameArea.keys[39]) {
myGamePiece.moveAngle = 2.5;
}
if (myGameArea.keys && myGameArea.keys[38]) {
myGamePiece.speed = 2.5;
}
if (myGameArea.keys && myGameArea.keys[40]) {
myGamePiece.speed = -1;
}
myGamePiece.newPos();
myGamePiece.update();
myGamePiece.hitBottom();
myGamePiece.hitTop();
myGamePiece.hitLeft();
myGamePiece.hitRight();
}

Categories