I'm only new to JavaScript and I'm having a problem with my code where I'm trying to move an object around the canvas with user input.
It works just fine using Firefox to run it but with Chrome the user input to move the square doesn't work and I was wondering why this is?
<!DOCTYPE html>
<html>
<head>
<canvas id = "gameCanvas" width="400" height="400" style = "border:1px solid #000000;"></canvas>
<style type="text/css"></style>
</head>
<body>
<script type="text/javascript">
var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "rgb(255, 0, 0)";
var snake = {
x: 5
, y: 5
};
function drawSnake() {
ctx.fillRect(snake.x ,snake.y,20,20);
}
window.addEventListener("keypress", function(event) {
if (event.keyCode == 39)
snake.x += 5;
else if (event.keyCode == 37)
snake.x -= 5;
else if (event.keyCode == 38)
snake.y -= 5;
else if (event.keyCode == 40)
snake.y += 5;
drawSnake();
});
drawSnake();
</script>
</body>
</html>
You have to change your keypress event to keydown to make it work in IE and Chromium based browsers.
Related
Hello I am trying to create a guitar hero sort of program with red circles appearing over a violin image when the corresponding key presses are pressed but I can't seem to be able to make them appear over the image even if I write the code after the canvas code. Can someone help me with this? I would also like to make the circles disappear after a while but timeout won't do the trick here because the image is not one color only for example changing the red circles to the background color after a while. How would i do this?
<html>
<head>
<title>Violin Hero</title>
<canvas id="myCanvas" width="1024" height="768"></canvas>
<style>
body {
background-image: url("violin.jpg");
background-size: 2500px 1300px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="1024" height="768"></canvas>
<img id="bow" src="bow.jpg" style="display:none;" />
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
window.addEventListener("keydown", soundPlay);
function fillRed() {
ctx.fillStyle = "red";
ctx.fill();
}
function keyQ(){
ctx.beginPath();
ctx.arc(1200, 300, 15, 0, Math.PI*2);
ctx.fillStyle = "red";
ctx.fill();
}
function keyW(){
ctx.beginPath();
ctx.arc(300, 300, 15, 0, Math.PI*2);
ctx.fillStyle = "red";
ctx.fill();
}
function keyE(){
ctx.beginPath();
ctx.arc(900, 500, 15, 0, Math.PI*2);
ctx.fillStyle = "red";
ctx.fill();
}
function keyR(){
ctx.beginPath();
ctx.arc(950, 100, 15, 0, Math.PI*2);
ctx.fillStyle = "red";
ctx.fill();
}
//var x = event.keyCode;
//<input type="text" onkeydown="pressedKey(event)">
function soundPlay(event) {
var x = event.keyCode;
if (x == 27) { // 27 is the ESC key
alert ("You pressed the Escape key!");
}
else if (x == 81) {
keyQ();
var sound = new Audio('1.mp3');
sound.play();
setTimeout(fillRed, 200);
}
else if (event.keyCode == 87) {
keyW();
var sound = new Audio("2.mp3");
sound.play();
setTimeout(fillRed, 200);
}
else if (event.keyCode == 69) {
keyE();
var sound = new Audio("3.mp3");
sound.play();
setTimeout(fillRed, 200);
}
else if (event.keyCode == 82) {
keyR();
var sound = new Audio("4.mp3");
sound.play();
setTimeout(fillRed, 200);
}
}
</script>
</body>
</html>
To bring something in front of images/To bring something always behind elements, one should use z-index.
Make a css for background image like this:
#backgroundImg{
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}
In this way, the background image will always be behind. Please check this or this for more details.
For your second question, I suggest you should make another post and keep this question focused on one issue only.
I've created a simple Plunkr example for you on how to achieve this kind of functionality in JS.
Click s, a or any other to show a red dot.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body id='mybody'>
<img id='violin' src='http://cdn.shopify.com/s/files/1/0704/3831/products/Antoni_Debut_Violin_Outfit_3677b25a-7618-46f7-9313-6080c2a51e27_grande.jpg?v=1444483336'>
<script>
document.addEventListener('keydown', (event) => {
console.log(event);
if (event.key.toLowerCase() === 's') {
showRedDot(110, 420);
} else if (event.key.toLowerCase() === 'a') {
showRedDot(150, 350);
} else {
showRedDot(200, 300);
}
});
var showRedDot = (top, left) => {
var oldDot = document.getElementById('redDot');
if (oldDot) {
oldDot.remove();
}
var dot = document.createElement('DIV');
dot.id = 'redDot';
dot.style.width = '10px';
dot.style.height = '10px';
dot.style.position = 'absolute';
dot.style.borderRadius = '100%';
dot.style.background = 'red';
dot.style.top = top + 'px';
dot.style.left = left + 'px';
document.getElementById('mybody').appendChild(dot);
};
</script>
</body>
</html>
Here's a working Plunkr
I tried to make it so that when my 'Player' reaches a jumpDistance of 50, it falls down, so he makes a small ' jump ' .
The code might not be exactly "clean" at this point, but I'm getting started with Javascript.
I made the player jump by using a for loop with a delay. I tried to make him go down the same way, but this didn't work out the way I planned.
Fiddle demo
** NOTE : Press space to start!
<!DOCTYPE html>
<html>
<style>
#canvas {
background-color: rgba(177, 177, 177, 1);
}
</style>
<body>
<div>
<p id="jumpDistance"></p>
<p id="jumpDirection"></p>
</div>
<canvas id="canvas" width="800" height="400"></canvas>
<script>
var canvas = document.querySelector('#canvas');
var context = canvas.getContext('2d');
var xPos = 150;
var yPos = 375;
var jumpDistance = 0;
function spelerObj() {
canvas.width=canvas.width;
context.rect(xPos, yPos, 25, 25);
context.stroke();
context.fillStyle = "#FF0000";
context.fillRect(xPos, yPos, 25, 25);
}
function jump(e) { //Here the player jumps, with a loop that calculates it's jump-distance.
//alert(e.keyCode);
if (e.keyCode == 32) {//
function upLoop() {
setTimeout(function () {
if(jumpDistance < 50) {
yPos -= 1;
jumpDistance++;
upLoop();
spelerObj();
document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
}
}, 1)
}
upLoop();
spelerObj();
}
}
document.onkeydown = jump;
</script>
</body>
</html>
You'd need a downloop that you can switch to at the top of the jump:
function upLoop() {
setTimeout(function() {
if (jumpDistance < 50) {
yPos -= 1;
jumpDistance++;
upLoop();
} else {
downLoop();
}
spelerObj();
document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
}, 1)
}
function downLoop() {
setTimeout(function() {
if (jumpDistance > 0) {
yPos += 1;
jumpDistance--;
downLoop();
}
spelerObj();
document.getElementById("jumpDistance").innerHTML = jumpDistance.toString();
}, 1)
}
Demo 1
You could also vary the timeout duration to add a pseudo-gravity effect.
Demo 2
I have been working on some HTML/Javascript Code and the main thing I want to have happen is when you press any of the arrow keys, the square that I drew moves that direction.
My general train of thought on what I have to do, is when I click on the key, it first clears the canvas, then redraws it with a different x and y value based on the function.
I tried that, but what happens is that the square just vanishes and I have no clue why.
I have been attempting to debug this for a while, and if anyone has any pointers I would love to here them!
<!DOCTYPE html>
<html>
<head>
<title> HTML </title>
<style>
canvas {
border: 1px solid #000000;
}
</style>
</head>
<body>
<center>
<canvas width = "620" height = "620" id = "myCanvas" ></canvas>
</center>
<script src = "script.js" > </script>
</body>
</html>
This is the Javascript Code (Sorry for not well formatting, still getting the hang of formatting code in StackOverflow)
document.addEventListener('keydown', function(event) {
if(event.keyCode == 37)
moveLeft();
if(event.keyCode == 39 )
moveRight();
if(event.keyCode == 38)
moveUp();
if(event.keyCode == 40)
moveDown();
});
function moveLeft() {
context.clearRect(0, 0, canvas.width, canvas.height);
//Edit X and Y Values
var newX, newY;
newX = squareX + 1;
newY = squareY;
context.rect(newX, newY, squareSizeX, squareSizeY);
context.fill(newX, newY, squareSizeX, squareSizeY);
}
function moveRight() {/* Needs to be Finished */}
function moveUp() {/* Needs to be Finished */}
function moveDown() {/* Needs to be Finished */}
var canvas;
var context;
var squareX, squareY;
var squareSizeX = 75;
var squareSizeY = 75;
function renderToCanvas() {
var didRender = false;
try {
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
/* INPUT DRAWING HERE */
//Drawing Square
squareX = canvas.width / 2;
squareY = canvas.height / 2;
context.rect(squareX, squareY, squareSizeX, squareSizeY);
context.fillRect(squareX, squareY, squareSizeX, squareSizeY);
context.stroke();
/* END DRAWING HERE */
didRender = true;
console.log("Rendered Drawing: " + didRender);
}
catch(err) {
console.log("Rendered Drawing: " + didRender);
console.log(err.message);
}
}
renderToCanvas();
In your moveLeft instead of this
context.rect(newX, newY, squareSizeX, squareSizeY);
context.fill(newX, newY, squareSizeX, squareSizeY);
Do this
context.fillRect(newX, newY, squareSizeX, squareSizeY);
Check out the docs for Canvas Context
You only use context.rect() or context.fill() when you are working on a path using context.beginPath()
Here is my code :
var ctx = document.getElementById("map").getContext("2d");
var ZeroX = 0;
var ZeroY = 0;
ctx.beginPath();
ctx.fillRect(100, 200, 100, 50); //Drawed a black rectangle
function moveMap(evt) {
var key = evt.keyCode || evt.which;
if (key == 38) { //UP
moveDirect(0, 20, false);
}
else if (key == 40) { //DOWN
moveDirect(0, 20, true);
}
else if (key == 39) { //RIGHT
moveDirect(20, 0, true);
}
else if (key == 37) { //LEFT
moveDirect(20, 0, false);
}
}
function moveDirect(X, Y, minus) {
if (minus == false) {
ZeroX -= X;
ZeroY -= Y;
}
else {
ZeroX += X;
ZeroY = Y;
}
var lol = ctx.getImageData(ZeroX, ZeroY, 3000, 3000);
ctx.clearRect(ZeroX, ZeroY, 3000, 3000);
ctx.putImageData(lol, 0, 0);
}
<body onkeypress="moveMap(event)">
<canvas id="map" width="500" height="500">Map </canvas>
</body>
If you run this snippet and click on one of the arrows on the keyboard, you'll see that the rectangle moves in the opposite
direction because I wanted to make like the screen was a camera in a
game. That's done on purpose
But if after you clicked on the arrow's oppsite (Up = Down, Left = Right,
etc), you will see that you must click two times to make it move in
the other direction. Try this with other arrows, still the same.
And if you press the same arrow many times, it's gap travelled becomes
bigger and bigger, but logically it must the same.
I want it to respond directly, not on two clicks and that the gap is always the same. Please explain in your answer why this is happennings. Thaks beforehand!
I am trying to create a simple HTML5 Canvas football game. The game has three options, The player chooses left, right or centre to kick a ball, the goal keeper is random and will dive left, right or stay in the centre. I want the user to press the left, right or up arrow keys to trigger the player to kick the ball but I can't get my code to recognise when the arrow keys are pressed. I have tried different keys which will work ie, the return key.
function canvasApp(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//Other Var's
document.onkeypress = function doKeyDown( e ) {
var key = e.keyCode;
if ( key == 37 ){
userChoice = key;
} else if (key == 38){
userChoice = key;
} else if (key == 39){
userChoice = key;
}
}
function draw() {
ctx.clearRect( 0, 0, canvas.width, canvas.height );
//------------------------------------------------
//Player shoots left
if ( userChoice == 37 ){
//More code
//------------------------------------------------
//Player shoots right
} else if ( userChoice == 39 ){
//More code
//------------------------------------------------
//Player shoots centre
} else if ( userChoice == 38 ) {
//More code
}
//------------------------------------------------
}
function gameLoop(){
window.setTimeout(gameLoop, framerate);
draw()
}
gameLoop();
}
document.onclick = function( e ){
window.clearTimeout();
}
If you need to see the full code let me know and I'll put a link up to a JSFiddle.
You're triggering the wrong event: use keydown even instead:
Check this page: http://help.dottoro.com/ljlkwans.php
The following is a snippet with jquery: if you use the keypress event it does not work.
<html>
<head>
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
$(document).ready(function(){
$(document).keydown(function(e){
var key = e.keyCode;
if ( key == 37 ){
console.log("left");
} else if (key == 38){
console.log("center");
} else if (key == 39){
console.log("right");
}
});
});
</script>
</html>