How to make canvas shape circle? - javascript

Hello I want to know how can I make the canvas shape circle in the below code.
The code is about moving a object with keyboard keys. I tried to make the circle out of this box but it just disappeared and i am not really sharp. Can some help me make this canvas circle without affecting code.
sorry but i have to write something more because SO says body has all code... i don't know what to say now (make the canvas circle)(make the canvas circle)(make the canvas circle)
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas id="myCanvas" width='800' height='800' border-radius= ></canvas>
</body>
</html>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;
let circle = new Path2D(); // <<< Declaration
circle.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'lightblue';
context.fill(circle); // <<< pass circle to context
context.lineWidth = 10;
context.strokeStyle = '#000066';
context.stroke(circle);
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
//event listener
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);
function onKeyDown(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = true;
break;
case 83: //s
keyS = true;
break;
case 65: //a
keyA = true;
break;
case 87: //w
keyW = true;
break;
}
}
function onKeyUp(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = false;
break;
case 83: //s
keyS = false;
break;
case 65: //a
keyA = false;
break;
case 87: //w
keyW = false;
break;
}
}
//neccessary variables
var tickX = 10;
var tickY = 10;
var keyW = false;
var keyA = false;
var keyS = false;
var keyD = false;
//main animation function
function drawStuff() {
window.requestAnimationFrame(drawStuff);
var canvas = document.getElementById("myCanvas");
var c = canvas.getContext("2d");
c.clearRect(0, 0, 800, 800);
c.fillStyle = "lightblue";
c.fillRect(tickX, tickY, 100, 100);
if (keyD == true) {
tickX += 1;
}
if (keyS == true) {
tickY += 1;
}
if (keyA == true) {
tickX--;
}
if (keyW == true) {
tickY--;
}
}
window.requestAnimationFrame(drawStuff);
</script>

I moved the circle code into the drawstuff function as that is where it has to run, and removed the use of fillRect.
You can see the result here:
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
//event listener
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);
function onKeyDown(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = true;
break;
case 83: //s
keyS = true;
break;
case 65: //a
keyA = true;
break;
case 87: //w
keyW = true;
break;
}
}
function onKeyUp(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = false;
break;
case 83: //s
keyS = false;
break;
case 65: //a
keyA = false;
break;
case 87: //w
keyW = false;
break;
}
}
//neccessary variables
var tickX = 10;
var tickY = 10;
var keyW = false;
var keyA = false;
var keyS = false;
var keyD = false;
//main animation function
function drawStuff() {
window.requestAnimationFrame(drawStuff);
var canvas = document.getElementById("myCanvas");
var c = canvas.getContext("2d");
c.clearRect(0, 0, 200, 200);
let circle = new Path2D(); // <<< Declaration
circle.arc(100 + tickX, 100 + tickY, 70, 0, 2 * Math.PI, false);
c.fillStyle = 'purple';
c.fill(circle); // <<< pass circle to context
c.lineWidth = 10;
c.strokeStyle = '#000066';
c.stroke(circle);
if (keyD == true) {
tickX += 1;
}
if (keyS == true) {
tickY += 1;
}
if (keyA == true) {
tickX--;
}
if (keyW == true) {
tickY--;
}
}
window.requestAnimationFrame(drawStuff);
Focus this area, then use keys <b>d, s, a, w</b><br />
<canvas id="myCanvas" width='200' height='200' style="border: 1px solid #f4f4f4" ></canvas>

Related

How to fix the direction and body problems?

i'm a rookie and i try to learn by myself from different sources html css and now i'm on the block of JS
I'm actually doing a snake game but i have differents issues , the body of my snake supposed to be 3 blocks width , and he is also supposed to move with the arrow key !!
I'm kind stuck and request your knowledge to let me find the light again :)
//* I'm french and hope my english is correct *//
window.onload = function()
{
var canvasWidth = 900;
var canvasHeight = 600;
var blockSize = 30;
var ctx;
var delay = 100;
var snakee;
init();
function init()
{
var canvas = document.createElement('canvas')
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.style.border = "1px solid"
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
snakee = new Snake([[6,4],[5,4],[4,4],[3,4],[2,4]], "right");
refreshCanvas();
}
function refreshCanvas()
{
ctx.clearRect (0,0,canvasWidth, canvasHeight);
snakee.draw();
snakee.advance();
setTimeout(refreshCanvas, delay);
}
function drawBlock(ctx, position)
{
var x = position[0] * blockSize;
var y = position[1] * blockSize;
ctx.fillRect(x ,y , blockSize , blockSize );
}
function Snake(body, _direction)
{
this.body = body;
this.direction = "right";
this.draw = function ()
{
ctx.save();
ctx.fillStyle = "#ff0000";
for(var i = 0; i < this.body.lenght; i++);
{
drawBlock(ctx, this.body[i]);
}
ctx.restore();
};
this.advance = function()
{
var nextPosition = this.body[0].slice();
switch(this.direction)
{
case "left":
nexPosition[0] -= 1;
break;
case "right":
nextPosition[0] += 1;
break;
case "down":
nextPosition[1] -= 1;
break;
case "up":
nextPosition[1] += 1;
break;
default:
throw("Invalid Direction");
}
this.body.unshift(nextPosition);
this.body.pop();
};
this.setDirection = function(newDirection)
{
var allowedDirections;
switch(this.direction)
{
case "left":
case "right":
allowedDirections = ["up", "donw"];
break;
case "down":
case "up":
allowedDirections = ["left","right"]
break;
default:
throw("Invalid Direction");
}
if(allowedDirections.indexOf(newDirection) > -1 )
{
this.direction = newDirection;
}
};
}
}
document.addEventListener = function handleKeyDown(e)
{
const key = e.keyCode;
var newDirection;
switch(key)
{
case 37:
newDirection = "left";
break;
case 38:
newDirection = "right";
break;
case 39:
newDirection = "up";
break;
case 40:
newDirection = "down";
break;
default:
return;
}
snakee.setDirection(newDirection);
}
addEventListener is a function and takes at least two arguments
it should be:
document.addEventListener('keydown', (e) => {
let code = e.keyCode;
})
Where the first arg is the type of event to handle and the second is the callback - handling the event.
I've noticed a few bugs in your code:
for(var i = 0; i < this.body.*lenght*; i++); << remove semicolon, lenght is typo
case "down":
nextPosition[1] -= 1; << should incrementing
break;
case "up":
nextPosition[1] += 1; << should decrementing
break;
Also the addEventListener code should be inside the window.onload statement
or else it will not see the snakee object.
This code simply won't work for a full blown snake program, because
each block of the snake can have a separate direction, but it's a start.

Javascript make the ball move

I am trying to make the ball move when I press space, but I can't seem to figure out how to do it.
It is vanilla Javascript with createjs libary. Can anybody help me and give me a little hint?
window.addEventListener('load', preload);
var canvas = document.getElementById('myCanvas');
var stage, queue;
var ball;
var paddle;
var settings = {
lives: 3,
points: 0,
speed: 3,
ballMovingSpeed: 7
}
var fingerDown = false;
var keys = {
left: false,
right: false,
shoot: false
}
var ballSettings = {
ballRadius: 10,
dx: 2,
dy: -2
}
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
function preload() {
"use strict";
stage = new createjs.Stage("myCanvas");
queue = new createjs.LoadQueue(true);
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", tickHappened);
drawPaddle();
drawBall();
window.addEventListener('keydown', keyDown);
window.addEventListener('keyup', keyUp);
}
function drawBall() {
"use strict"
ball = new createjs.Shape();
ball.graphics.beginFill('red').drawCircle(0, 0, 10);
stage.addChild(ball);
ball.x = 400;
ball.y = 535;
canvasHeight += ballSettings.dy;
canvasWidth += ballSettings.dx;
}
// paddle Movement
//--------------------------------*
function keyDown(e) {
"use strict";
console.log(e.keyCode);
switch (e.keyCode) {
case 37:
keys.left = true;
break;
case 39:
keys.right = true;
break;
case 32:
keys.shoot = true;
break;
}
}
function keyUp(e) {
"use strict";
switch (e.keyCode) {
case 37:
keys.left = false;
break;
case 39:
keys.right = false;
break;
case 32:
keys.shoot = false;
break;
}
}
function movePaddle() {
"use strict";
if (keys.left) {
paddle.x -= settings.speed;
if (paddle.x < 0 + paddle.regX) {
paddle.x = 0 + paddle.regX;
}
} else if (keys.right) {
paddle.x += settings.speed;
if (paddle.x > canvasWidth - paddle.width + paddle.regX) {
paddle.x = canvasWidth - paddle.width + paddle.regX;
}
} else if (keys.shoot) {
console.log("shoot ball");
if (canvasWidth + ballSettings.dx > canvas.width - ballSettings.ballRadius || canvasWidth + ballSettings.dx < ballSettings.ballRadius) {
ballSettings.dx = -ballSettings.dx;
}
if (canvasHeight + ballSettings.dy > canvas.height - ballSettings.ballRadius || canvasHeight + ballSettings.dy < ballSettings.ballRadius) {
ballSettings.dy = -ballSettings.dy;
}
}
}
function tickHappened(e) {
"use strict";
movePaddle();
stage.update(e);
}
So in order to have your object move, you need a few things. First, you need to re-draw it, which you seem to have set to re-draw 60 times per second. Next, you have to update the position of your object. Your ball needs two things for that, a velocity X and a velocity Y. With each tick, you'll set the ball.x += ball.velX so that each time it'll move it's position along with it's moving velocity, and once it hits something just set the ball.velX = -ball.velX.
I'm not sure what project you're working on but I'm assuming it is somewhat similar to pong, if you'd like to review or use some of the code I used on my own pong game feel free - http://pongio.bitballoon.com/

Can't Make a Player Two

I am trying to add a second player to javascript game but the code isn't working. I need some instruction on how to follow through with this. The second player doesn't need to be fancy, a different color square would suffice. My current player is the green square. Any information would be helpful thank you.
var myObstacle;
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
function startGame() {}
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 700,
height =600,
player = {
x : 1,
y : 7,
width : 25,
height : 25,
speed: 10,
velX: 0,
velY: 0,
jumping: false
},
keys = [],
friction = .9,
gravity = .8;
canvas.width = width;
canvas.height = height;
function update(){
// check keys
if (keys[38] || keys[32]) {
// up arrow or space
if(!player.jumping){
player.jumping = true;
player.velY = -player.speed*.1;
}
}
if (keys[39]) {
// right arrow
if (player.velX < player.speed) {
player.velX++;
}
}
if (keys[37]) {
// left arrow
if (player.velX > -player.speed) {
player.velX--;
}
}
player.velX *= friction;
player.velY += gravity;
player.x += player.velX;
player.y += player.velY;
if (player.x >= width-player.width) {
player.x = width-player.width;
} else if (player.x <= 0) {
player.x = 0;
}
if(player.y >= height-player.height){
player.y = height - player.height;
player.jumping = false;
}
ctx.clearRect(0,0,width,height);
ctx.fillStyle = "green";
ctx.fillRect(player.x, player.y, player.width, player.height);
requestAnimationFrame(update);
}
document.body.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load",function(){
update();
});
<html>
<head>
<title>Square Stairs™</title>
</head>
<body bgcolor="#000">
<canvas id="canvas" style="border:3px solid #fff"></canvas>
</body>
</html>
Please help if you can, Thank You.
Use a little bit of OOP:
var myObstacle;
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
function Player(color){
this.x = 1;
this.y = 7
this.width = 25
this.height= 25
this.speed= 10
this.velX= 0
this.velY= 0
this.jumping= false
this.color = color;
}
function startGame() {}
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 700,
height =600,
player = new Player('green'),
player2 = new Player('red')
keys = [],
friction = .9,
gravity = .8;
canvas.width = width;
canvas.height = height;
function update(){
// check keys
if (keys[38] || keys[32]) {
// up arrow or space
if(!player.jumping){
player.jumping = true;
player.velY = -player.speed*.1;
}
}
if (keys[39]) {
// right arrow
if (player.velX < player.speed) {
player.velX++;
}
}
if (keys[37]) {
// left arrow
if (player.velX > -player.speed) {
player.velX--;
}
}
player.velX *= friction;
player.velY += gravity;
player.x += player.velX;
player.y += player.velY;
if (player.x >= width-player.width) {
player.x = width-player.width;
} else if (player.x <= 0) {
player.x = 0;
}
if(player.y >= height-player.height){
player.y = height - player.height;
player.jumping = false;
}
player2.velY += gravity;
player2.x += player2.velX;
player2.y += player2.velY;
if (player2.x >= width-player2.width) {
player2.x = width-player2.width;
} else if (player2.x <= 0) {
player2.x = 0;
}
if(player2.y >= height-player2.height){
player2.y = height - player2.height;
player2.jumping = false;
}
ctx.clearRect(0,0,width,height);
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
ctx.fillStyle = player2.color;
ctx.fillRect(player2.x, player2.y, player2.width, player2.height);
requestAnimationFrame(update);
}
document.body.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load",function(){
update();
});
<html>
<head>
<title>Square Stairs™</title>
</head>
<body bgcolor="#000">
<canvas id="canvas" style="border:3px solid #fff"></canvas>
</body>
</html>
Okay, I couldn't resist... I added even more OOP. So, now you can add as many players as you'd like. The important distinction is the color and the key mappings. My example (arbitrarily) adds three players:
var players=[];
players.push(new Player('green', {
32: 'jump',
37: 'left',
38: 'jump',
39: 'right'
}))
players.push(new Player('red', {
56: 'jump',
52: 'left',
54: 'right'
}, width-25))
players.push(new Player('blue', {
87: 'jump',
65: 'left',
68: 'right'
}, (width-25)/2))
var myObstacle;
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
function startGame() {}
function Player(color,keymap,x) {
this.x = (typeof x === 'undefined') ? 1 : x;
this.y = 7;
this.width = 25;
this.height = 25;
this.speed = 10;
this.velX = 0;
this.velY = 0;
this.jumping= false;
this.keymap = {}
for (let key in keymap) {
switch (keymap[key]) {
case 'jump':
this.keymap[key] = this.jump
break;
case 'left':
this.keymap[key] = this.moveLeft
break;
case 'right':
this.keymap[key] = this.moveRight
break;
}
}
this.color = color;
} // Player()
Player.prototype.jump=function () {
if (!this.jumping) {
this.jumping = true;
this.velY = -this.speed*1.5;
}
}
Player.prototype.moveRight = function () {
if (this.velX < this.speed) {
this.velX++;
}
}
Player.prototype.moveLeft = function () {
if (this.velX > -this.speed) {
this.velX--;
}
}
// Globals
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 700,
height =600,
keys = [],
friction = .9,
gravity = .8;
canvas.width = width;
canvas.height = height;
// Set up players
var players=[];
players.push(new Player('green', {
32: 'jump',
37: 'left',
38: 'jump',
39: 'right'
}))
players.push(new Player('red', {
56: 'jump',
52: 'left',
54: 'right'
}, width-25))
players.push(new Player('blue', {
87: 'jump',
65: 'left',
68: 'right'
}, (width-25)/2))
function update() {
ctx.clearRect(0,0,width,height);
players.forEach(player => {
// check player-specific keys
for (let i in player.keymap)
{
if (keys[i] && typeof player.keymap[i] === 'function')
player.keymap[i].bind(player)();
}
player.velX *= friction;
player.velY += gravity;
player.x += player.velX;
player.y += player.velY;
if (player.x >= width-player.width) {
player.x = width-player.width;
} else if (player.x <= 0) {
player.x = 0;
}
if (player.y >= height-player.height) {
player.y = height - player.height;
player.jumping = false;
}
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}) // player.forEach
requestAnimationFrame(update);
}
document.body.addEventListener("keydown", function(e) {
// console.log(e.keyCode);
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load",function(){
update();
});
html>
<head>
<title>Square Stairs™</title>
</head>
<body bgcolor="#000">
<canvas id="canvas" style="border:3px solid #fff"></canvas>
</body>
</html>

javascript how to change variable on keyboard click

I have been trying to make my first game in javascript, its a pong like game where two players move their rectangles around to bump the ball in the other direction. I want it so that when player one hits the "a" key, their character moves left, when they hit the d key they move right.
Right now, nothing happens when I click the desired keys.
This is my current code:
$(document).ready(function() {
// things needed
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//positions of elements at start
var ballposx = 400;
var ballposy = 50;
var balldx = 1;
var balldy = 2;
var balld2x = 0;
var balld2y = 0;
var p1posx = 80;
var p1posy = 225;
var p1dx = 0;
var p1dy = 0;
var p2posx = 620;
var p2posy = 225;
var p2dx = 0;
var p2dy = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
//goal1
ctx.fillStyle = "#0F3F0F";
var goal1 = ctx.fillRect(0, 150, 50, 150);
//goal2
ctx.fillStyle = "#204050";
var goal2 = ctx.fillRect(750, 150, 50, 150);
ctx.beginPath();
//ball
var ball = ctx.arc(ballposx, ballposy, 60, 0, 2 * Math.PI);
ctx.stroke();
//p1
ctx.fillStyle = "#FF0000";
var p1 = ctx.fillRect(p1posx, p1posy, 40, 75);
//p2
ctx.fillStyle = "#0000FF";
var p1 = ctx.fillRect(p2posx, p2posy, 40, 75);
p1posx += p1dx;
p2posx += p2dx;
balldx += balld2x;
balldy += balld2y;
ballposx += balldx;
ballposy += balldy;
$(window).keypress(function(e) {
var code = e.which;
switch (code) {
case 65:
p1dx = 1;
case 68:
p1dx = -1;
case 37:
p2dx = -1;
case 39:
p2dx = 1;
default:
break;
}
});
if (ballposy === 240) {
balldy = -1;
} else if (ballposy === 60) {
balldy = 1;
} else if (ballposx === 60) {
balldx = 1;
} else if (ballposx === 740) {
balldx = -1;
} else if (ballposx === p1posx && ballposy < p1posy) {
balldx = 1;
} else if (ballposx === p2posx && ballposy < p2posy) {
balldx = -1;
}
}
setInterval(draw, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<canvas id="myCanvas" width="800px" height="300px" style="border:1px solid #000000;"> Sorry your browser doesnt support this!</canvas></center>
You're adding another keypress handler every 10 ms. So after a few seconds there are thousands of handlers running every time you press a key, and this is probably bogging down the browser. You should just bind the handler once, outside the draw function.
And in the function, you need break statements in each case.
Your code tests are also wrong. Lowercase a is 97, not 65. And the values of p1dx are backwards -- if you want to go left, it should be -1, not 1.
$(document).ready(function() {
// things needed
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//positions of elements at start
var ballposx = 400;
var ballposy = 50;
var balldx = 1;
var balldy = 2;
var balld2x = 0;
var balld2y = 0;
var p1posx = 80;
var p1posy = 225;
var p1dx = 0;
var p1dy = 0;
var p2posx = 620;
var p2posy = 225;
var p2dx = 0;
var p2dy = 0;
$(window).keypress(function(e) {
var code = e.which;
switch (code) {
case 97:
p1dx = -1;
break;
case 100:
p1dx = 1;
break;
case 37:
p2dx = -1;
break;
case 39:
p2dx = 1;
break;
default:
break;
}
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
//goal1
ctx.fillStyle = "#0F3F0F";
var goal1 = ctx.fillRect(0, 150, 50, 150);
//goal2
ctx.fillStyle = "#204050";
var goal2 = ctx.fillRect(750, 150, 50, 150);
ctx.beginPath();
//ball
var ball = ctx.arc(ballposx, ballposy, 60, 0, 2 * Math.PI);
ctx.stroke();
//p1
ctx.fillStyle = "#FF0000";
var p1 = ctx.fillRect(p1posx, p1posy, 40, 75);
//p2
ctx.fillStyle = "#0000FF";
var p1 = ctx.fillRect(p2posx, p2posy, 40, 75);
p1posx += p1dx;
p2posx += p2dx;
balldx += balld2x;
balldy += balld2y;
ballposx += balldx;
ballposy += balldy;
if (ballposy === 240) {
balldy = -1;
} else if (ballposy === 60) {
balldy = 1;
} else if (ballposx === 60) {
balldx = 1;
} else if (ballposx === 740) {
balldx = -1;
} else if (ballposx === p1posx && ballposy < p1posy) {
balldx = 1;
} else if (ballposx === p2posx && ballposy < p2posy) {
balldx = -1;
}
}
setInterval(draw, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<canvas id="myCanvas" width="800px" height="300px" style="border:1px solid #000000;"> Sorry your browser doesnt support this!</canvas></center>
I didn't check the whole code, but ou should add the break; statement in every case, not just the default.
For example, your code should be something like:
$(window).keypress(function(e){
var code = e.which;
switch (code)
{
case 65:
p1dx = 1;
break;
case 68:
p1dx = -1;
break;
case 37:
p2dx = -1;
break;
case 39:
p2dx = 1;
break;
default:
break;
}
});

Using Dialog Box to Reset Canvas

I am trying to use Javascript to reset my canvas to its original state. But the action does nothing when Ok is pressed. It gives me a dialog box when it is pressed, but it does not reset the canvas to its original state.
<!DOCTYPE html>
<html>
<head>
<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;
var aKey = false;
var sKey = false;
var wKey = false;
var dKey = false;
var enterKey = false;
var bX = 100;
var bY = 100;
var sideLengthZ = 10;
var ctx;
window.onload = function() {
c = document.getElementById("myCanvas");
c.width = window.innerWidth * 0.9;
c.height = window.innerHeight * 0.9;
ctx = c.getContext('2d');
window.setInterval(function() {
draw();
draw2();
}, GAME_SPEED);
}
document.onkeyup = function(event) {
event.preventDefault();
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;
case 65:
aKey = false;
break;
case 83:
sKey = false;
break;
case 68:
dKey = false;
break;
case 87:
wKey = false;
break;
case 13:
enterKey = false;
break;
}
}
document.onkeydown = function(event) {
event.preventDefault();
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;
case 65:
aKey = true;
break;
case 83:
sKey = true;
break;
case 68:
dKey = true;
break;
case 87:
wKey = true;
break;
case 13:
enterKey = true;
break;
}
}
function draw() {
if (leftKey == true) {
x--;
}
if (rightKey == true) {
x++;
}
if (upKey == true) {
y--;
}
if (downKey == true) {
y++;
}
if (spaceKey == true) {
sideLength++;
}
ctx.fillStyle = "#000000";
ctx.fillRect(x, y, sideLength, sideLength);
}
function draw2() {
if (aKey == true) {
bX--;
}
if (dKey == true) {
bX++;
}
if (wKey == true) {
bY--;
}
if (sKey == true) {
bY++;
}
if (enterKey == true) {
sideLengthZ++;
}
var b = document.getElementById("myCanvas");
var cntxt2 = ctx;
ctx.fillStyle = "#F00000";
ctx.fillRect(bX, bY, sideLengthZ, sideLengthZ);
}
function itReset()
{
var erase = confirm("Are you sure you want to delete?");
if (erase == true)
context.clearRect();
else
return false;
}
var ctx = document.querySelector("myCanvas").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, 500); // fill area
}
</script>
</head>
<body>
<!--Marlon Jacques -->
<canvas id="myCanvas" style="border: 5px solid">
Your browser does not support the canvas element.
</canvas>
<button onclick="itReset()">Reset</button>
</body>
</html>
Use context.clearRect to clear the canvas.
Note that you need to get the context for your canvas because the context has the drawing (and clearing) methods--the canvas element itself does not have those methods.
function itReset(){
var erase = confirm("Are you sure you want to delete?");
if (erase == true){
ctx.clearRect(0,0,c.width,c.height);
}else{
return false;
}

Categories

Resources