a border where you can not go through (canvas game) - javascript

I have to make a game for school :)
I'am a beginner in Javascript (and English) and I have a question about a canvas.
I made a spaceship in my canvas, and I can fly around with it with my arrowkeys. The problem is that my spaceship can fly trough the border of my canvas.. and thats not way it ment to be.
I hope one of you guys can help me with it! :)
Here is my code..
window.onload = init;
var ctx;
var x = 750;
var y = 400;
var up = false;
var right = false;
var left = false;
var gravity = -1.1;
var horizontalSpeed = 0.1;
function init() {
document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;
var canvas = document.querySelector("canvas");
ctx = canvas.getContext("2d");
animate();
}
function animate() {
moveShip();
drawScene();
requestAnimationFrame(animate);
}
function drawScene(){
ctx.clearRect(0,0,1600,800);
drawSpaceship();
}
function moveShip() {
if (left) {
horizontalSpeed -= 0.1;
}else if (right){
horizontalSpeed += 0.1;
}
if (up) {
gravity -=0.4;
}
gravity += 0.12;
y += gravity;
x += horizontalSpeed;
}
function drawSpaceship () {
ctx.save();
ctx.translate(x, y);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -40);
ctx.lineTo(30,-80);
ctx.lineTo(60,-40);
ctx.lineTo(60,0);
ctx.lineTo(80,30);
ctx.lineTo(80,90);
ctx.lineTo(60,50);
ctx.lineTo(0,50);
ctx.lineTo(-20,90);
ctx.lineTo(-20,30);
ctx.lineTo(0,0);
ctx.strokeStyle = 'white';
ctx.stroke();
ctx.closePath();
ctx.restore();
}
function handleKeyDown (evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 37:
left = true;
break;
case 38:
up = true;
break;
case 39:
right = true;
break;
}
}
function handleKeyUp(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 37:
left = false;
break;
case 38:
up = false;
break;
case 39:
right = false;
break;
}
}

You need a concept called "clamping".
Clamping is limiting a value within a specified range.
You want to clamp your ship's horizontal position to be no less than 0 and no greater than the canvas width.
You want to clamp your ship's vertical position to be no less than 0 and no greater than the canvas height.
This is code to clamp a value between a min and max value.
clampedValue = Math.min(Math.max(currentValue, min), max);
To keep any [x,y] within the canvas, you can clamp the x,y like this:
clampedX = Math.min(Math.max(x, 0), canvasWidth);
clampedY = Math.min(Math.max(y, 0), canvasHeight);
Now your ship is larger than just a single [x,y] point. So to keep your entire ship inside your canvas you would clamp the [x,y] like this:
y += gravity;
x += horizontalSpeed;
x=Math.min(Math.max(x,0+20),width-80);
y=Math.min(Math.max(y,0+80),height-90);
Also, you're letting gravity increase even if you ship is on the ground. At that point the gravity effect becomes zero because the ship is being entirely supported by the ground against gravity. Therefore, you'll want to set gravity to zero when the ship is on the ground:
if(y==height-90){gravity=0;}
Here's your code refactored to keep your ship inside the canvas:
var x = 200;
var y = 100;
var up = false;
var right = false;
var left = false;
var gravity = -1.1;
var horizontalSpeed = 0.1;
var canvas = document.querySelector("canvas");
var width=canvas.width;
var height=canvas.height;
var ctx = canvas.getContext("2d");
init();
function init() {
document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;
animate();
}
function animate() {
moveShip();
drawScene();
requestAnimationFrame(animate);
}
function drawScene(){
ctx.clearRect(0,0,1600,800);
drawSpaceship();
}
function moveShip() {
if (left) {
horizontalSpeed -= 0.1;
}else if (right){
horizontalSpeed += 0.1;
}
if (up) {
gravity -=0.4;
}
gravity += 0.12;
y += gravity;
x += horizontalSpeed;
x=Math.min(Math.max(x,0+20),width-80);
y=Math.min(Math.max(y,0+80),height-90);
if(y==height-90){gravity=0;}
}
function drawSpaceship () {
ctx.save();
ctx.translate(x, y);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -40);
ctx.lineTo(30,-80);
ctx.lineTo(60,-40);
ctx.lineTo(60,0);
ctx.lineTo(80,30);
ctx.lineTo(80,90);
ctx.lineTo(60,50);
ctx.lineTo(0,50);
ctx.lineTo(-20,90);
ctx.lineTo(-20,30);
ctx.lineTo(0,0);
ctx.strokeStyle = 'blue';
ctx.stroke();
ctx.closePath();
ctx.restore();
}
function handleKeyDown (evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 37:
left = true;
break;
case 38:
up = true;
break;
case 39:
right = true;
break;
}
}
function handleKeyUp(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 37:
left = false;
break;
case 38:
up = false;
break;
case 39:
right = false;
break;
}
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<h4>Hold down the arrow keys to move the ship.</h4>
<canvas id="canvas" width=500 height=400></canvas>

Related

Player Speeding Up In JavaScript Game [duplicate]

This question already has an answer here:
setInterval time increases on every click
(1 answer)
Closed 1 year ago.
Every single time I move with the right or left arrows keys or A or D, the player speeds up. I don't want this to happen. I want the player to move at the same speed whenever you press the move key. I have no idea why this is happening. Here is my code:
class Player {
constructor(x, y, color, width, height, health, strength, type, speed) {
this.x = x;
this.y = y;
this.color = color;
this.width = width;
this.height = height;
this.health = health;
this.strength = strength;
this.type = type;
this.speed = speed;
}
draw() {
c.beginPath();
c.rect(this.x, this.y, this.width, this.height);
c.fillStyle = this.color;
c.fill();
c.stroke();
}
moveLeft(){
this.x -= this.speed;
}
moveRight(){
this.x += this.speed;
}
moveUp(){
this.y += this.speed;
}
}
var x = canvas.width / 2;
var y = canvas.height / 2;
var left = false;
var up = false;
var right = false;
var left2 = false;
var up2 = false;
var right2 = false;
var pressing;
var player = new Player(x, y, 'red', 30, 30, 100, 30, 'basic', 2);
player.draw();
document.addEventListener('keydown', function(e) {
switch (e.keyCode) {
case 37:
left = true;
setInterval(function pressing(){
if(left2===false && left === true){
player.moveLeft();
}
},10)
break;
case 65:
left2 = true;
setInterval(function pressing(){
if(left===false && left2 === true){
player.moveLeft();
}
},10)
break;
case 39:
right = true;
setInterval(function pressing(){
if(right2===false && right === true){
player.moveRight();
}
},10)
break;
case 68:
right2 = true;
setInterval(function pressing(){
if(right===false && right2 === true){
player.moveRight();
}
},10)
break;
}
});
document.addEventListener("keyup", event => {
clearInterval(pressing);
if (event.keyCode === 37) {
left = false;
}
if (event.keyCode === 65) {
left2 = false;
}
if (event.keyCode === 39) {
right = false;
}
if (event.keyCode === 68) {
right2 = false;
}
});
I followed many tutorials but couldn't find a different easy way to move my player. Does anyone have another strategy for moving or know why this isn't working?
On every keypress you are currently creating a new interval that is never stopped. So what you are actually doing is to create duplicate intervals each time the key is pressed. As a first, rough fix you could try to store the return value of setInterval in a variable outside of the scope of the key event handler and check whether you have earlier intervals running. If so, clear them up before going ahead.
As clearInterval does not throw any error when fed un-intervalish values, you don't even have to check before clearing:
let myInterval = null
document.addEventListener('keydown', (e) => {
// Clean up any earlier mess.
clearInterval(myInterval)
// Create new mess.
myInterval = setInterval(() => { /* do something */ }, 10)
})
I think that you already have the answer...
You are creating multiple intervals that are never stopped.
But I would not use the interval in the key events, instead use just one outside to draw at certain frequency, then use a more mathematical approach to move and set the speed of the player on those events, we don't need different functions to move left or right, all we need is the correct speed value, positive increases (moves right), negative decreases (moves left) ... here is the code:
class Player {
constructor(pos, speed) {
this.pos = pos
this.speed = speed
}
draw() {
this.pos.x += this.speed.x
this.pos.y += this.speed.y
c.clearRect(0, 0, canvas.width, canvas.height)
c.beginPath()
c.rect(this.pos.x, this.pos.y, 20, 20)
c.fill()
}
}
let canvas = document.getElementById("game")
let c = canvas.getContext("2d")
var player = new Player({ x: 60, y: 50 }, { x: 0, y: 0 })
setInterval(() => player.draw(), 50)
document.addEventListener("keydown", function (e) {
switch (e.keyCode) {
case 37:
case 65:
player.speed.x = -1
break
case 39:
case 68:
player.speed.x = 1
break
}
})
document.addEventListener("keyup", function (e) {
switch (e.keyCode) {
case 37:
case 65:
case 39:
case 68:
player.speed.x = 0
break
}
})
<canvas id="game"></canvas>
I did simplify a lot of your code to keep this example small...
If you are really serious about building a JS game you should look at some of the game engines:
https://github.com/collections/javascript-game-engines
Those are some of the most popular open source ones

Issues with HTML canvas and object oriented JavaScript character for HTML game

The issue is, the HTML canvas is not outputting a character object inside the canvas. The canvas is defined as the gameArea and the character is defined as a character. Both have been written in JavaScript, and the character is made into an object.
This is for a 2D platformer game, so far I have tried to change the character form an object to a variable to see whether the encapsulation of the object was causing issues, but this has not worked. I have also tried to add a new function within the character object called update, in order to make sure the character (rectangle) is filled when moving.
Here is my code:
The first section declares the character variable, and also has a function, which is started first in the HTML using onload:
var Character;
function startGame(){
gameArea.start();
Character = new character(40, 80, "#4286f4", 30, 500, true, 0, 0);
}
The parameters for the character object are width, height, colour, x, y, jumping state, speedX and speedY (also shown later on in the code).
The second section shows the gameArea variable (the canvas), I have also called my EventListeners of Keydown and Keyup here:
var gameArea = {
canvas: document.getElementById("canvas"), //Defining the canvas'
//dimensions
start: function() {
this.canvas.width = 700;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {//EventListener
functions
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
The next section is the character object:
function character(width, height, color, x, y, jumping, speedX, speedY)
{//Character object, blue rectangle
this.jumping=jumping;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = speedX;
this.speedY= speedY;
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.width, this.height, this.x, this.y);
this.update = function() {//Updating the gameArea function
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
To my knowledge, the code above is the only relevant code to the issue. If needed the rest of the code (the controller logic and movement mechanics) can be found below:
function updateGameArea() {
gameArea.clear();
character.speedX = 0;
character.speedY = 0;
character.update();
var controller = {
up: false,
down: false,
left: false,
right: false,
keyListener: function (event) {
var keyPosition = (event.type == "keydown") ? true : false;
switch (event.keyCode) {
case 87:
controller.up = keyPosition;
break;
case 83:
controller.down = keyPosition;
break;
case 65:
controller.left = keyPosition;
break;
case 68:
controller.right = keyPosition;
break;
}
}
};
if (controller.up && character.jumping == false) {
character.speedY -= 2.5
character.jumping = true;
}
if (controller.down) {
character.speedY += 2.5;
}
if (controller.left) {
character.speedX -= 2.5;
}
if (controller.right) {
character.speedX += 2.5;
}
character.speedY += 1.5;
character.x = character.speedX;
character.y = character.speedY;
character.speedX *= 0.9;
character.speedY *= 0.9
var ground = gameArea.canvas.height - this.height;
if (this.y > ground) {
character.jumping = false;
character.y = ground;
character.speedY = 0;
}
}
Expected results: character displays inside the canvas and has the correct movement
Actual results: character does not display.
I understand that there is a lot of code here, but I would really appreciate it if someone could point me in the correct direction, as I don't really understand why the character does not display in the canvas.
Thanks a lot!
You are setting the character's position to 500 so he is drawn outside of the visible area (the canvas is only 500 tall).
x= 0, y= 0 is in the top right in a canvas.
Change Character = new character(40, 80, "#4286f4", 30, 500, true, 0, 0);
To Character = new character(40, 80, "#4286f4", 30, 400, true, 0, 0);
EDIT: Rewrote the whole thing.
var character, ctx;
function startGame() {
gameArea.start();
character = new Character(40, 80, "#4286f4", 30, 400, true, 0, 0);
gameArea.clear();
updateGameArea();
}
let gameArea = {
start() {
this.canvas = document.getElementById("canvas"); //Defining the canvas'
this.canvas.width = 700;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
},
clear() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
}
function Character(width, height, color, x, y, jumping, speedX, speedY) { //Character object, blue rectangle
this.jumping = jumping;
this.width = width;
this.height = height;
this.position = {
x,
y
};
this.velocity = {
x: speedX,
y: speedY
};
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.width, this.height, this.x, this.y);
this.color = color;
return this;
}
Character.prototype = {
update() { //Updating the gameArea function
character.position.x += character.velocity.x;
character.position.y += character.velocity.y;
let ground = gameArea.canvas.height - this.height;
if (this.position.y > ground) {
character.jumping = false;
character.position.y = ground;
character.velocity.y = 0;
}
ctx = gameArea.context;
ctx.fillStyle = this.color;
ctx.fillRect(this.position.x, this.position.y, this.width, this.height);
}
}
var controller = {
x: 0,
y: 0
};
document.addEventListener('keydown', e => {
switch (e.keyCode) {
case 87:
controller.y = -1;
break;
case 83:
controller.y = 1;
break;
case 65:
controller.x = -1;
break;
case 68:
controller.x = 1;
break;
}
});
document.addEventListener('keyup', e => {
switch (e.keyCode) {
case 87:
controller.y = 0;
break;
case 83:
controller.y = 0;
break;
case 65:
controller.x = 0;
break;
case 68:
controller.x = 0;
break;
}
});
function updateGameArea() {
gameArea.clear();
character.velocity.x = controller.x;
character.velocity.y = controller.y;
character.update();
requestAnimationFrame(updateGameArea);
}
window.onload = startGame;
canvas {
width:100%;
}
<canvas id="canvas"></canvas>

Moving Image is lagging on Canvas with Keydown [duplicate]

The "spaceShip" in the following code isn't moving smoothly at the beginning of holding any arrow key down. It moves one step, freezes for a split second, and then moves "smoothly". How can I make it move smoothly right from the beginning, with not "freezing"?
My code:
<!doctype html>
<html>
<head>
<meta http-content="Content-type" charset="utf-8">
<title>Make body move smoothly</title>
<style type="text/css">
body {
}
canvas {
margin: auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="600"></canvas>
<script type="text/javascript">
// Set up requestAnimationFrame and cancelAnimationFrame
(function() {
var lastTime =0;
var vendors=['ms', 'moz', 'webkit', 'o'];
for(var x=0; x<vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame=window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+ 'CancelAnimationFrame'] ||
window[vendors[x] +'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame=function(callback, element) {
var currTime =new Date().getTime();
var timeToCall =Math.max(0, 16 - (currTime - lastTime));
var id =window.setTimeout(function() { callback(currTime+timeToCall); },
timeToCall);
lastTime =currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame=function(id) {
clearTimeout(id);
};
}());
var canvas;
var ctx;
// ship data
var shipPositionX = document.getElementById('canvas').width/2;
var shipPositionY = document.getElementById('canvas').height - 30;
var deltaShipPositionX = 10;
var deltaShipPositionY = 10;
function init() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
draw();
}
function draw(){
clear();
createRectangleToCoverCanvas();
createSpaceShip(shipPositionX, shipPositionY, 10);
requestAnimationFrame(draw);
}
function clear(){
ctx.clearRect(0, 0, document.getElementById('canvas').width, document.getElementById('canvas').height);
}
function createRectangleToCoverCanvas(){
ctx.fillStyle = 'black';
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function createSpaceShip(x, y, radius) {
ctx.fillStyle = 'white'
ctx.strokeStyle = 'white'
ctx.beginPath();
ctx.rect(x, y, 20, 20);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function moveSpaceShip(event){
switch(event.keyCode){
// left
case 37:
if(shipPositionX - deltaShipPositionX + 15 > 0){
shipPositionX -= deltaShipPositionX;
}
break;
// up
case 38:
if(shipPositionY - deltaShipPositionY + 15 > 0){
shipPositionY -= deltaShipPositionY;
}
break;
// right
case 39:
if(shipPositionX + deltaShipPositionX < document.getElementById('canvas').width){
shipPositionX += deltaShipPositionX;
}
break;
//down
case 40:
if(shipPositionY + deltaShipPositionY < document.getElementById('canvas').height){
shipPositionY += deltaShipPositionY;
}
break;
}
}
window.addEventListener('load', init);
window.addEventListener('keydown', moveSpaceShip, true);
</script>
</body>
</html>
Notice the difference between my code and this example: http://atomicrobotdesign.com/blog_media/sprite_sheet/spritesheet.html
See how the example's is smooth, but my "spaceShip" isn't?
Why is it happening and how can I fix it? Is it because the example uses a sprite (but this doesn't seem to make much sense)?
The problem is that you wait for each keydown event to update the ship position.
The keydown event has a delay before it triggers again : the delay you are experiencing at beginning and the jump you face at each redraw.
The solution here is to trigger the movement on keydown and release it on keyup. This way, your ship will move smoothly as soon as you push the button.
// Im' assuming most of visitors here have recent browsers, so I removed the rAF polyfill for readibility
// If you wrap it after the canvas element decalaration, you can already populate this variable, it will avoid that you make a lot of calls to document.getElementById()
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// ship data
var shipPositionX = canvas.width / 2;
// Just for the snippet height
var shipPositionY = 0;
var deltaShipPositionX = 10;
var deltaShipPositionY = 10;
//Removed the init() function, since our elements are loaded.
function draw() {
clear();
createRectangleToCoverCanvas();
createSpaceShip(shipPositionX, shipPositionY, 10);
}
function clear() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function createRectangleToCoverCanvas() {
ctx.fillStyle = 'black';
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fill();
ctx.stroke();
}
function createSpaceShip(x, y, radius) {
ctx.fillStyle = 'white'
ctx.strokeStyle = 'white'
ctx.beginPath();
ctx.rect(x, y, 20, 20);
ctx.fill();
ctx.stroke();
}
// instantiate a variable that will store our animationFrame id, so we can cancel it further
var raf,
// the direction object, with an x and y values
direction = {
x: 0,
y: 0
};
// we can set a speed variable
var speed = 2.5;
function triggerMoveSpaceShip(event) {
switch (event.keyCode) {
// left
case 37:
// update the direction object
direction.x = -speed;
// avoid the scroll in the snippet
event.preventDefault();
break;
// up
case 38:
direction.y = -speed;
event.preventDefault();
break;
// right
case 39:
direction.x = speed;
event.preventDefault();
break;
//down
case 40:
direction.y = speed;
event.preventDefault();
break;
}
// if we haven't initiated the animation yet, and that our direction is not 0, then do it now
if (!raf && (direction.x || direction.y)) moveSpaceShip();
}
function releaseMoveSpaceShip(event) {;
switch (event.keyCode) {
// left
case 37:
//reset this direction
direction.x = 0;
break;
// up
case 38:
direction.y = 0;
break;
// right
case 39:
direction.x = 0;
break;
//down
case 40:
direction.y = 0;
break;
}
if (!direction.x && !direction.y) {
// if none of the directions is set, stop the animation
cancelAnimationFrame(raf);
raf = undefined;
}
}
function moveSpaceShip() {
// declare our animation function
var move = function() {
// update the positions without going out of the screen
// Sorry, this is dirty...
if(direction.x){
if(
(shipPositionX > 0 && shipPositionX < canvas.width-20) ||
(shipPositionX <= 0 && direction.x > 0) ||
(shipPositionX >= canvas.width-20 && direction.x < 0))
shipPositionX += direction.x;
}
if(direction.y){
if(
(shipPositionY > 0 && shipPositionY < canvas.height-20) ||
(shipPositionY <= 0 && direction.y > 0) ||
(shipPositionY >= canvas.width-20 && direction.y < 0))
shipPositionY += direction.y;
}
// finally draw ou ship
draw();
// update our raf id
raf = requestAnimationFrame(move);
};
// let's go !
raf = requestAnimationFrame(move);
}
draw();
window.addEventListener('keydown', triggerMoveSpaceShip, true);
window.addEventListener('keyup', releaseMoveSpaceShip, true);
canvas {
margin: auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
border: 1px solid black;
}
body{
overflow: none;
}
<canvas id="canvas" width="400" height="200"></canvas>
uncommented fiddle

Creating a Rainbow Effect in Rectangle Canvas

I would like to know how to create a rainbow effect in my canvas in the fill style, like for it to change colors at certain intervals or when I continually press a key. Like from red to blue, etc, similar to how you can add a rainbow effect to text.
<script type="text/javascript">
var GAME_SPEED = 1000/60; //game rate
var x = 100;
var y = 100;
var sideLength = 10;
var leftKey = false;
var rightKey = false;
var upKey = false;
var downKey = false;
var spaceKey = false;
window.onload = function()
{
c = document.getElementById("marCanvas2");
c.width = window.innerWidth*0.9;
c.height = window.innerHeight*0.9;
window.setInterval("draw()" , GAME_SPEED);
}
document.onkeyup = function(event)
{
switch(event.keyCode)
{
case 37: leftKey =false;
break;
case 39: rightKey = false;
break;
case 38: upKey = false;
break;
case 40: downKey = false;
break;
case 32: spaceKey = false;
break;
}
}
document.onkeydown = function(event)
{
switch(event.keyCode)
{
case 37: leftKey =true;
break;
case 39: rightKey = true;
break;
case 38: upKey = true;
break;
case 40: downKey = true;
break;
case 32: spaceKey = true;
break;
}
}
function draw()
{
if(leftKey == true)
{
x--;
}
if(rightKey == true)
{
x++;
}
if(upKey == true)
{
y--;
}
if(downKey == true)
{
y++;
}
if(spaceKey == true)
{
sideLength++;
}
var c = document.getElementById("marCanvas2");
var cntxt = c.getContext("2d");
cntxt.fillStyle= " ";
cntxt.fillRect(x, y, sideLength, sideLength);
}
</script>
</head>
<body>
<!--Marlon Jacques -->
<canvas id="marCanvas2" style="border: 5px solid
#000000;">
Your browser does not support the canvas element.
</canvas>
</body>
</html>
You can do this by dynamically defining the start and end of the gradient. What colors you want is up to you, but you can use for example HSL color model to "rotate" through a color range with different speed for start and end.
Example 1
var ctx = document.querySelector("canvas").getContext("2d"),
angleA = Math.random() * 360, // start angle (for HSL)
angleB = Math.random() * 360,
stepA = 1.2, stepB = 0.7; // "speed" for change
function createGradient() {
var gr = ctx.createLinearGradient(0, 0, 500, 0); // create gradient
gr.addColorStop(0, "hsl(" + (angleA % 360) + ",100%, 50%)"); // start color
gr.addColorStop(1, "hsl(" + (angleB % 360) + ",100%, 50%)"); // end color
ctx.fillStyle = gr; // set as fill style
ctx.fillRect(0, 0, 500, 150); // fill area
}
// demo loop
(function anim() {
createGradient();
ctx.clearRect(8,8,484,134);
// =========> DRAW YOUR FRONT OBJECTS HERE <=========
angleA += stepA; // increase angles
angleB += stepB;
requestAnimationFrame(anim)
})();
<canvas width=500></canvas>
In the demo above the start and end colors are more or less random, you can instead just give one a head start so the other follows:
Example 2
var ctx = document.querySelector("canvas").getContext("2d"),
angle = Math.random() * 360, // start angle (for HSL)
angleDlt = 60, // 60° ahead
step = 1; // "speed" for change
function createGradient() {
var gr = ctx.createLinearGradient(0, 0, 500, 0); // create gradient
gr.addColorStop(0, "hsl(" + (angle % 360) + ",100%, 50%)"); // start color
gr.addColorStop(0.5, "hsl(" + ((angle + (angleDlt/2)) % 360) + ",100%, 50%)");
gr.addColorStop(1, "hsl(" + ((angle + angleDlt) % 360) + ",100%, 50%)");
ctx.fillStyle = gr; // set as fill style
ctx.fillRect(0, 0, 500, 150); // fill area
}
// demo loop
(function anim() {
createGradient();
ctx.clearRect(8,8,484,134);
angle += step; // increase angles
requestAnimationFrame(anim)
})();
<canvas width=500></canvas>

How to move an object using X and Y coordinates in JavaScript

I am making a 2-Dimensional baseball game with JavaScript and HTML5 and I am trying to move an image that I have drawn with JavaScript like so:
//canvas
var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");
//baseball
var baseball = new Image();
baseball.onload = function() {
ctx.drawImage(baseball, 400, 425);
};
baseball.src = "baseball2.png";
I'm not sure how I would move it though, I have seen many people seem to just type something like ballX and ballY but I don't understand where the actual x and y definition comes from. Here is my code so far:
http://jsfiddle.net/xRfua/
Thanks in advance for any help at all!
Store the balls position in a couple of variables and then you can translate based on these values before drawing your object, something like this should work:
var baseballX = 0;
var baseballY = 0;
var goLeft = 0;
var goRight = 0;
var goUp = 0;
var goDown = 0;
var ballSpeed = 5;
function renderCanvas() {
// clear the canvas
ctx.clearRect(0, 0, c.width, c.height);
ctx.save();
if(goLeft) baseballX -= ballSpeed;
if(goRight) baseballX += ballSpeed;
if(goUp) baseballY -= ballSpeed;
if(goDown) baseballY += ballSpeed;
// translate to balls position
ctx.translate(baseballX, baseballY);
// draw the image
ctx.drawImage(baseball, 0, 0);
ctx.restore();
}
// handle any user input
window.addEventListener('keyup', function(event) {
switch (event.keyCode) {
case 37: // Left
goLeft = 0;
break;
case 38: // Up
goUp = 0;
break;
case 39: // Right
goRight = 0;
break;
case 40: // Down
goDown = 0;
break;
}
}, false);
window.addEventListener('keydown', function(event) {
switch (event.keyCode) {
case 37: // Left
goLeft = 1;
break;
case 38: // Up
goUp = 1;
break;
case 39: // Right
goRight = 1;
break;
case 40: // Down
goDown = 1;
break;
}
}, false);
// set off timer
setInterval(renderCanvas, 1000 / 100);
Here is a working example: fiddle

Categories