Javascript how to make object appear over a background image - javascript

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

Related

Im just playing around with HTML but when I load my code, I get an error. Error Code: Out of Memory

the code is short and it cant be because of outdated systems as this laptop was bought 4 months ago.
Every time I click on the index.html file it takes 50 seconds to load and then I get the error. I am not sure what else to do as the Microsoft Help Team was useless. I am not sure if there are any errors in the code as I can't run it. Any help is appreciated.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>A canvas</title>
</head>
<style type="text/css">
canvas {
border: 1px solid black;
}
</style>
<body>
<canvas id="canvas" height="1000px" width="1000px"></canvas>
<script>
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');
canvas.addEventListener('mousedown', onDown, false);
var fireWall = false;
var score = 0;
while (score != 10){
c.font = "30px Comic Sans MS"
c.fillText(score, 500, 200)
c.font = "30px Comic Sans MS"
c.fillText("Click the Screen 10 Times to Win the Hardest Game Ever!!!", 50,300);
function onDown(){
console.log('working')
c.score++;
}
if(score === 10){
fireWall = true;
break;
}
}
if(fireWall === true){
c.fill(255, 153, 0);
c.noStroke();
c.ellipse(mouseX-90, mouseY-30, 75, 25);
c.ellipse(mouseX-90, mouseY-80, 85, 35);
c.rect(mouseX-103, mouseY-80, 25,45);
c.rect(mouseX-132, mouseY-155, 85,75);
c.textSize(50);
c.fill(255,0,0);
c.text("YOU WON", mouseX-205, mouseY-170);
}
</script>
</body>
</html>
com/jywPv.png
const c = document.getElementById('canvas').getContext('2d');
const game = { // You could use an Object literal to store stuff
fireWall: false,
score: 0,
mouseX: 0,
mouseY: 0,
};
const draw = () => { // Create a function to handle drawing
// Don't forget to clear the canvas before painting
c.clearRect(0, 0, c.canvas.width, c.canvas.height);
c.font = "30px Comic Sans MS";
if (game.fireWall) {
c.fillText("YOU WON", game.mouseX-80, game.mouseY-5);
} else {
c.fillText(game.score, 500, 200); // Retrieve the score from game Object
c.fillText("Click the Screen 10 Times to Win the Hardest Game Ever!!!", 50, 300);
}
}
const onDown = (ev) => { // Don't forget the ev Event!
if (game.fireWall) return; // Prevent additional clicks if firewall reached
const bcr = c.canvas.getBoundingClientRect();
game.mouseX = ev.clientX - bcr.x;
game.mouseY = ev.clientY - bcr.y;
game.score++;
if (game.score >= 10) {
game.fireWall = true;
}
draw();
}
draw(); // First draw!
c.canvas.addEventListener('mousedown', onDown); // And draw on click
canvas {
border: 1px solid black;
}
<canvas id="canvas" height="1000px" width="1000px"></canvas>

How can I reverse the direction of an element on a canvas?

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

The Process of Clearing and Redrawing a Square on a HTML Canvas

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()

Moving an Object in a HTML5 Canvas with User Input

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.

Toggle Onclick Issue in Javascript

Simply put, I'm trying to toggle a button to make a line bold (or not). I read a few questions here similar to this problem, but the solutions haven't helped me. Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div id="DrawLineDiv">
<canvas id="DrawLineCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('DrawLineCanvas');
var context = canvas.getContext('2d');
// Use beginPath() to declare that a new path is to be drawn
context.beginPath();
// Place the drawing cursor at the desired point
context.moveTo(100, 150);
// Determine where to stop drawing
context.lineTo(450,50);
//Draw the line
context.stroke();
</script>
</div>
<script>
var canvas = document.getElementById("DrawLineCanvas");
//var context = canvas.getContext('2d');
function toggleLineBold(button) {
var button;
if (button == "BoldNow") {
context.lineWidth = 15;
context.stroke();
document.getElementById("BoldLineButton").onclick = function(){
toggleLineBold('Regular');
};
} else {
context.lineWidth = 1;
context.stroke();
document.getElementById("BoldLineButton").onclick = function(){
toggleLineBold('BoldNow');
};
return;
};
};
</script>
<div id="BoldLineButton" style="height:50px; width:120px; border:2px solid #6495ed; background-color:#bcd2ee; border-radius:10px; margin-left: 5px; text-align:center" onclick="toggleLineBold('BoldNow')">
<br/>Toggle Bold Line<br/>
</div>
</body>
</html>
The line changes to bold, but triggers an error in the javascript at the line trying to change the onclick event. I know I've got something wrong, I'm just not sure what.
Thank's in advance for your assistance.
LIVE DEMO
HTML:
<canvas id="DrawLineCanvas" width="578" height="200"></canvas>
<button id="BoldLineButton">Line size: <b>1</b></button>
JS:
var doc = document,
canvas = doc.querySelector('#DrawLineCanvas'),
boldBtn = doc.querySelector('#BoldLineButton'),
ctx = canvas.getContext('2d'),
size = [1, 3, 5, 10, 15], // use only [1, 15] if you want
currSize = 0; // size[0] = 1 // Index pointer to get the value out of the
// size Array
function draw(){
canvas.width = canvas.width;
ctx.beginPath();
ctx.moveTo(100, 150);
ctx.lineTo(450,50);
ctx.lineWidth = size[currSize]; // Use currSize Array index
ctx.stroke();
}
draw();
function toggleLineBold() {
++currSize; // Increase size and
currSize %= size.length; // loop if needed.
boldBtn.getElementsByTagName('b')[0].innerHTML = size[currSize];
draw();
}
boldBtn.addEventListener("click", toggleLineBold);

Categories