Creating a square with mousedown - javascript

I want a red square to appear where I click on the canvas with my mouse, but I'm having trouble getting the square to appear on the canvas when I click on it. The function start contains window.addEventListener() which is supposed to be creating a component on the mouseclick, but I'm not sure if I am missing something or if I'm just completely wrong.
<!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="start() {
gameArea.start();
}
var gameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 840;
this.canvas.height = 540;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
//I don't know what Im doing wrong here
window.addEventListener('mousedown', function (e) {
new component(30, 30, "red", 10, 120);
})
}
}
//and here
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
}
</script>
</html>

window.addEventListener('mousedown', (e) => {
const {layerX, layerY} = e;
const rectSize = 30;
this.context.fillStyle = 'red';
this.context.fillRect(layerX - rectSize / 2, layerY - rectSize / 2, rectSize, rectSize);
});
you passed a function () {} which had no context of your gameArea. The other part is a canvas api.

Related

Styling text onscreen using the <p> tag using JavaScript

I am developing a game using JavaScript and I want to have the scenes of a classic 1990's game where the text appears in split-second intervals then disappears once the user clicks next. Is there a way to do this just using JavaScript?
I'm using PhpStorm for the moment. I have yet to start as I'm designing the blueprints with my friend. I am also a bit confused about where to start because I have searched for methods but no luck.
Since You Are Making A Game You Will Be Having A Canvas Too
So Use This Code If have Any Questions Ask Me
HTML
<!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()">
</body>
</html>
Javascript
<script>
var myGamePiece;
var myTitle;
//Function To Start the Game
function startGame() {
myTitle = new component("20px", "Consolas", "black", 150, 135, "text");
myGameArea.start();
}
// myGameArea Is The Canvas in Which The Whole Drawing Process Will be Drawn & The Title Is Drawn In This Too
var myGameArea = {
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;
// setInterval Function Draws the Canvas 50 times in a Second You Can Change The Value Of 50 IF You Want
this.interval = setInterval(updateGameArea, 50);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
}
// Component Function Makes a New Component Like We Have A Title By Component Function
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
// This Checks if Component Type is Text And Every Frame is Divided By 70 Then Nothing Will Happen Else Your Title Will Appear You Glitch is Because Of This Function You Can The Value As You Want
if (this.type == "text" && everyinterval(70) ) {
} else {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
}
}
}
// This Function Updates GameArea (The Canvas) I Added The Frame No So You Can See The Glitch At Every Frame Number
function updateGameArea() {
myGameArea.frameNo += 1;
myGameArea.clear();
myTitle.text = "Title Glitching at " + myGameArea.frameNo;
myTitle.update();
}
// The Function To Make The Glitch Which Divide's The FrameNo By "n" Number
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
</script>
Hope This Helps!

why are my sprites not drawing?

I am learning how to make a minigame with javascript, but my player is not rendered.
I donĀ“t know why. I am not getting any errors.
The startGame() starts with
How should I edit my code to get it to run and get the sprites to render?
Here's my code :
<html>
<head>
<meta name="viewport" content="width = device-width, initial-scale = 1.0"/>
</head>
<body onload='startGame()'>
<script>
function startGame() {
createCanvas.start();
}
let ninja = new Image();
let ninjaImage = "images/player/stand01.png"
const createCanvas = {
canvas : document.createElement('canvas'),
start() {
this.canvas.width = 600;
this.canvas.height = 400;
this.context = this.canvas.getContext('2d');
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
}
}
function sprite(options){
let that = {};
that.context = options.context;
that.width = options.width;
that.height = options.height;
that.image = options.image;
return that;
that.render = function () {
that.context.drawImage(
that.image, 0, 0, that.width, that.height, 0, 0, that.width, that.height);
}
player.render();
}
player = sprite ({
width: 100,
height: 100,
image: ninjaImage
});
</script>
</body>
<style>
canvas {
border: 1px solid black;
background: grey;
}
</style>
Assuming you have taken care of the early return, your code isn't working because you are likely because your render() function is being called when your player object is created. Before you can draw anything it's better to setup your canvas and context object first.
My recommendation for creating objects in a class like way is to use the function/prototype approach.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
display: block;
margin: auto;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
void function() {
"use strict";
/*
In JS a 'class' is made up of two things
A constructor function that attaches individual properties to every new instance
(When a contructor is called with 'new' I.E. 'new Sprite()', the 'this' variable in the constructor
is assigned to the newly created object.
The other part is a prototype that holds shared properties between instances of
the 'class'. (in an instance prototype values are accessible via the this keyword).
*/
// Constructor function
function Sprite(x,y,width,height,image) {
this.x = x || 0.0;
this.y = y || 0.0;
this.width = width || 1.0;
this.height = height || 1.0;
this.image = image || null;
}
// Prototype object (Shared between instances)
Sprite.prototype = {
render: function(ctx) {
if (this.image) {
ctx.drawImage(this.image,this.x,this.y,this.width,this.height);
} else {
ctx.fillStyle = "darkred";
ctx.fillRect(this.x,this.y,this.width,this.height);
}
}
};
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var sprite = null;
var image = new Image();
image.src = "https://i.stack.imgur.com/WnNgY.png";
// window.onload, called when page has loaded
onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
sprite = new Sprite(65,55,50,50,image);
sprite.render(ctx);
}
}();
</script>
</body>
</html>

Moving an image with arrow keys in JavaScript

I'm making a simple Javascript game for a school project. I'm trying to replace the red square with an image(in the following link).
enter link description here
How can i achieve this?
Great question! Use a snippet to post your code. This link should provide a complete answer add image
var myGamePiece;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myGameArea.start();
}
var myGameArea = {
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.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.newPos();
myGamePiece.update();
}
function moveup() {
myGamePiece.speedY -= 1;
}
function movedown() {
myGamePiece.speedY += 1;
}
function moveleft() {
myGamePiece.speedX -= 1;
}
function moveright() {
myGamePiece.speedX += 1;
}
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body onload="startGame()">
<div style="text-align:center;width:480px;">
<button onclick="moveup()">UP</button><br><br>
<button onclick="moveleft()">LEFT</button>
<button onclick="moveright()">RIGHT</button><br><br>
<button onclick="movedown()">DOWN</button>
</div>
<p>If you click a button the red square will start moving. Click the same button many times, and it will move faster and faster.</p>
</body>
</html>

nothing is drawn on page using javascript and canvas

I am trying to develop a game and i am starting to dip my toes into the HTML <canvas> tag and using it with javascript. My program here is my work in progress clone of PONG. I have managed to add the two paddles with no error but as i have added the Ball function it simply refuses to draw anything on the screen and thus i am given a page covered in black.
Could it be because i am using classes?
Here is the code:
// ctx.fillStyle = 'rgba(red, green, blue, alpha)';
// ctx.fillRect(x, y, width, height);
var canvas;
var ctx;
var dx = 5;
var dy = 5;
//Class Definitions
function Game(width, height, colour) {
this.width = width;
this.height = height;
this.colour = colour;
}
function Player(width, height, colour, x, y, up, down) {
this.width = width;
this.height = height;
this.colour = colour;
this.x = x;
this.y = y;
this.up = up;
this.down = down;
this.move = function(ny) {
this.y = this.y + ny;
ctx.fillStyle = this.colour;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
}
function Ball(width, height, colour, x , y, isTouched, isInGoal) {
this.width = width;
this.height = height;
this.colour = colour;
this.x = x;
this.y = y;
this.isTouched = isTouched;
this.isInGoal = isInGoal;
this.move = function() {
clear();
this.x = this.x + 1;
ctx.fillStyle = this.colour;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
}
//Creating new Classes
var gameStage = new Game((window.innerWidth), (window.innerHeight), 'rgb(0,0,0)');
var paddleOne = new Player(10, 150, 'rgb(255,255,255)', (gameStage.width/10), (gameStage.height/2), 38, 40);
var paddleTwo = new Player(10, 150, 'rgb(255,255,255)', (gameStage.width/1.1), (gameStage.height/2), 87, 83);
var ball = new Ball(20, 20, 'rgb(255,255,255)', (gameStage.width/2), (gameStage.height/2), 0, 0);
//Initialisation
function init(){
canvas = document.getElementById('game');
canvas.setAttribute('width', gameStage.width);
canvas.setAttribute('height', gameStage.height);
canvas.setAttribute('tabindex', 0);
if (game.getContext){
ctx = canvas.getContext('2d');
return setInterval(ball.move, 10);
return setInterval(draw, 10);
}
}
//Canvas Functions
function clear(){
ctx.clearRect(0, 0, gameStage.width, gameStage.height);
}
function draw() {
clear();
ctx.fillStyle = gameStage.colour;
ctx.fillRect(0, 0, gameStage.width, gameStage.height);
ctx.fillStyle = paddleOne.colour;
ctx.fillRect(paddleOne.x, paddleOne.y, paddleOne.width, paddleOne.height);
ctx.fillStyle = paddleTwo.colour;
ctx.fillRect(paddleTwo.x, paddleTwo.y, paddleTwo.width, paddleTwo.height);
console.log("PlayerOne Y Coordinate: " + paddleOne.y + "\n");
console.log("PlayerTwo Y Coordinate: " + paddleTwo.y + "\n");
}
//Player Control
function doKeyDown(e) {
if (e.keyCode == paddleOne.up){
paddleOne.move(-5);
} else if (e.keyCode == paddleOne.down) {
paddleOne.move(5);
} else if (e.keyCode == paddleTwo.up) {
paddleTwo.move(-5);
} else if (e.keyCode == paddleTwo.down) {
paddleTwo.move(5);
}
}
//For HTML
function beginStuff(){
init();
window.addEventListener('keydown', doKeyDown, true);
}
* { margin: 0; padding: 0;}
body, html {height: 100%;}
#game {
position: absolute;
width:100%;
height:100%;
background-color: #000000;
}
<!DOCTYPE HTML>
<htmL>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>A game</title>
<script type="text/javascript" src="game.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload="beginStuff();" >
<canvas id="game">
Please upgrade your browser to support HTML5. <br/>
</canvas>
</body>
</htmL>
This looks wrong to me:
return setInterval(ball.move, 10);
return setInterval(draw, 10);
Firstly, you've got 2 returns. Secondly, you've lost the binding on the move method:
return setInterval(ball.move.bind(ball), 10);
If that doesn't fix it I suggest stepping through in a debugger, line-by-line, making sure that everything is doing exactly what you expect it to.
With help from #skirtle, i moved the ball.move(); to the draw() function and removed the clear() call from the ball.move() function.

Image not showing in javascript

When running my program I have an image I want to draw on the mouse's x position(clientX) and y position(clientY).
When running the program regularly by not using client x and y in the position for being drawn, it works just fine.
This is the image
//variables
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var player = new Image();
player.src = "http://i.stack.imgur.com/P9vJm.png";
//functions
function start() {
setInterval(update, 10);
}
function update() {
clearRender();
render();
}
function clearRender() {
ctx.clearRect(0,0,1300,500);
}
function render() {
var mx = document.clientX;
var my = document.clientY;
ctx.drawImage(player, mx, my);
}
#canvas {
height: 500px;
width: 1300px;
background-color: black;
position: absolute;
left: 25px;
top: 50px;
}
body {
background-color: white;
}
<!DOCTYPE html>
<html>
<head>
<title> Space Invaders </title>
<link rel="stylesheet" type="text/css" href="invader.css">
</head>
<body>
<canvas id="canvas"> </canvas>
<script type="text/javascript" src="invader.js"></script>
</body>
</html>
To get you started, you would need an event handler to get your mouse position
c.addEventListener('mousemove', update, false);
JS:
//variables
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var player = new Image();
player.src = "http://i.stack.imgur.com/P9vJm.png";
c.addEventListener('mousemove', update, false);
//functions
function start() {
setInterval(update, 10);
}
function update(e) {
//clearRender();
render(e);
}
function clearRender() {
ctx.clearRect(0, 0, 1300, 500);
}
function render(e) {
var pos = getMousePos(c, e);
posx = pos.x;
posy = pos.y;
ctx.drawImage(player, posx, posy);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
Here's a fiddle: https://jsfiddle.net/vwbo8k6k/
This might help you understand more about mouse positions, but I hope the image shows this time.
http://stackoverflow.com/a/17130415/2036808

Categories

Resources