I'm trying to create a timer within an object - however when trying to increment the counter by the time that's passed I'm getting a NaN error. The error stops if I replace the deltaTime argument with a constant, but then the jump time would vary depending upon the end users machine and work load.
class Actor {
constructor() {
this.jumpCounter = 0
this.jumpTimer = function (deltaTime) {
console.log(this.jumpCounter);
this.jumpCounter += deltaTime;
console.log(deltaTime)
}
}
}
let canvas = document.getElementById('gameScreen');
let ctx = canvas.getContext("2d");
var lastTime = 0;
const GAME_WIDTH = 600;
const GAME_HEIGHT = 600;
actor = new Actor;
function gameLoop(timestamp) {
let deltaTime = timestamp - lastTime;
lastTime = timestamp;
ctx.fillStyle = 'rgba(155, 200, 155, 0.3)'
ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
actor.jumpTimer(deltaTime)
requestAnimationFrame(gameLoop);
}
gameLoop();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Sandbox</title>
<style>
#gameScreen {
border: 1px solid;
}
</style>
</head>
<body>
<canvas id="gameScreen" width="600" height="600"></canvas>
<script></script>
</body>
</html>
As the error resulted from there being on timestamp on the first run through of the code this fixed the issue:
this.jumpTimer = function (deltaTime) {
if (!deltaTime) return;
console.log(this.jumpCounter);
this.jumpCounter += deltaTime;
console.log(deltaTime)
}
Related
I am Japanese and I apologize for my unnatural English, but I would appreciate it if you could read it.
I learned how to convert paperscript to javascript from the official documentation.
Its means are as follows
Change the type attribute of the script tag to text/paperscript. <script type="text/paperscript" src="./main.js"></script>
Enable Paperscope for global use.  paper.install(window)
Specify the target of the canvas. paper.setup(document.getElementById("myCanvas"))
Write the main code in the onload window.onload = function(){ /* add main code */ }
Finally, add paper.view.draw()
The onFrame and onResize transforms as follows. view.onFrame = function(event) {}
onMouseDown, onMouseUp, onMouseDrag, onMouseMove, etc. are converted as follows. var customTool = new Tool(); customTool.onMouseDown = function(event) {};
I have tried these methods, but applying these to the Examples on the paper.js official site does not work correctly.
The following code is the result of trying these.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://unpkg.com/paper"></script>
<script type="text/javascript" src="./main.js"></script>
<title>Document</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
</html>
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function(){
paper.setup(myCanvas)
var points = 25;
// The distance between the points:
var length = 35;
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++)
path.add(start + new Point(i * length, 0));
customTool.onMouseMove=function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
var vector = segment.point - nextSegment.point;
vector.length = length;
nextSegment.point = segment.point - vector;
}
path.smooth({ type: 'continuous' });
}
customTool.onMouseDown=function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp=function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
The original paperscript can be found here.
What is the problem with this code?
Thank you for reading to the end!
The var vector in the for loop is not getting the correct values in your code. Change the math operators and it will work like the paperjs demo.
Math operators (+ - * /) for vector only works in paperscript. In Javascript, use .add() .subtract() .multiply() .divide(). see http://paperjs.org/reference/point/#subtract-point
// paperscript
segment.point - nextSegment.point
// javascript
segment.point.subtract(nextSegment.point)
Here's a working demo of your example
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function() {
paper.setup(myCanvas)
var points = 15; //25
// The distance between the points:
var length = 20; //35
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++) {
path.add(start + new Point(i * length, 0));
}
customTool.onMouseMove = function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
//var vector = segment.point - nextSegment.point;
var vector = segment.point.subtract(nextSegment.point);
vector.length = length;
//nextSegment.point = segment.point - vector;
nextSegment.point = segment.point.subtract(vector);
}
path.smooth({
type: 'continuous'
});
}
customTool.onMouseDown = function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp = function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
html,
body {
margin: 0
}
canvas {
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://unpkg.com/paper"></script>
<!-- you can add this back in -->
<!-- <script type="text/javascript" src="./main.js"></script> -->
<title>Document</title>
</head>
<body>
<!-- set any size you want, or use CSS/JS to make this resizable -->
<canvas id="myCanvas" width="600" height="150"></canvas>
</body>
</html>
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>
First I just want to say thank you to everyone that has been helping me on this site. It's really helping my confidence with javascript.
I am building an audio/visual app that should play a different sound every time the user clicks. Every time the user clicks, the animation restarts as well and so on. My issue is that I plan on inserting 5-10 sounds that I have designed myself and I would like them to loop with every click. Meaning click once, soun1 plays. Click again, sound 2 plays. So in my mind, I should create a for loop with an array of the sounds. Simple idea, but I have no idea how to do this in vanilla js let alone p5. I'm working with p5 because I might want to add audio effects later on. Anyway, this is what I have tried below. I can play a single sound just fine, and feel like I am on the right track, but I keep getting errors like .play() is not defined.
I know the syntax below is wayyyy off in the loop area. I just started throwing everything at the wall.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="resources\p5.js"></script>
<script src="resources\p5.dom.js"></script>
<script src="resources\p5.sound.js"></script>
<script type="text/javascript" src="js\app.js"></script>
<link rel="stylesheet" href="css\style.css">
<title>Breathe</title>
</head>
<body>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
let outerDiam = 0;
let cnv;
let px;
let py;
let bgColor;
let sound1;
let sound2;
let sound3;
let sound4;
let sound5;
let allSounds;
function centerCanvas() {
let x = (windowWidth - width) / 2;
let y = (windowHeight - height) / 2;
cnv.position(x, y);
}
function setup() {
sound1 = loadSound('https://www.dl.dropboxusercontent.com/s/hkg7jnhfwic842j/bubbles.mp3?dl=0', loaded);
sound2 = loadSound('https://www.dl.dropboxusercontent.com/s/9el41r25exizbwl/clay.mp3?dl=0', loaded);
sound3 = loadSound('https://www.dl.dropboxusercontent.com/s/8o5rgfknx0do8ps/confetti.mp3?dl=0', loaded);
sound4 = loadSound('https://www.dl.dropboxusercontent.com/s/g5auzxd6lkk522a/corona.mp3?dl=0', loaded);
sound5 = loadSound('https://www.dl.dropboxusercontent.com/s/pc73ig27wmmnc4l/dotted-spiral.mp3?dl=0', loaded);
cnv = createCanvas(windowWidth, windowHeight);
cnv.style('display', 'block');
centerCanvas();
bgColor = random(150, 255);
}
function loaded() {
console.log('song is loaded');
}
function windowResized() {
centerCanvas();
}
function draw() {
background(bgColor);
for (let i = 0; i < 5; i++){
let diam = outerDiam - 30 * i;
if (diam > 0) {
let fade = map(diam, 0, width, 0, 255);
stroke(fade);
noFill();
ellipse(px, py, diam);
}
}
outerDiam = outerDiam + 2;
}
function mousePressed() {
outerDiam = 0;
px = random(width);
py = random(height);
bgColor = random (150, 255);
// if (!sound1.isPlaying()) {
// sound1.play();
// sound1.play();
// } else {
// sound1.pause();
// }
allSounds = [sound1, sound2, sound3, sound4, sound5];
let newSound = [];
for (let i = 0; i < allSounds.length; i++) {
allSounds[i].push(newSound);
allSounds[i].play();
}
}
Not a P5 expert, but you can do this using plain Javascript, using the Audio class:
var audio = new Audio("path/to/audio");
audio.loop = true; //loop
audio.play(); //play
Then, whenever you want to change track:
audio.pause(); //stop playing old track
audio.currentTime = 0; //rewind
audio.src = "path/to/new_track" //change track
audio.play() //play
I'm currently undergoing the development of a game, but I've stumbled across a problem where the fillRect() command will not work onto the HTML5 canvas, using Javascript. I do not know why this is happening, after trying to do research on it and checking my code. The HTML code is shown below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cube Quest</title>
<style>
#game {
border: 1px dashed black;
}
</style>
</head>
<body>
<canvas id="game" width='1280' height='720'>Your browser does not support the canvas element in HTML5.</canvas>
<script>
var clicked = false; // Mouse handling event
var mouseX = event.cilentX; // Mouse X coordinate
var mouseY = event.cilentY; // Mouse Y coordinate
var canvas = document.getElementById("game"); // For canvas
var ctx = canvas.getContext("2d"); // For canvas
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(10, 10, 150, 80);
</script>
</body>
</html>
I'm not the best expert on Javascript, so there is little that I know which could help me understand the reason why no rectangle shows when the code is correct.
I appreciate the help on this specific question in advance. :)
You will need to look addEventListener function in JS to made better view of situation.
Here working example :
// globals
var canvas = document.getElementById("game");
var clicked = false; // Mouse handling event
var mouseX = 0;
var mouseY = 0;
// yuor application parameters
var app = {
clearCanvas: true,
title: 'HELLO'
};
canvas.addEventListener('click' , function (event){
mouseX = event.pageX; // Mouse X coordinate
mouseY = event.pageY; // Mouse Y coordinate
console.log("Mouse x : " + mouseX + " Mouse y :" + mouseY );
drawAgain();
});
// Initial draw
var ctx = canvas.getContext("2d"); // For canvas
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(mouseX, mouseY, 350, 65);
ctx.font="30px Arial";
ctx.fillStyle = 'lime';
ctx.fillText(app.title + "X:" + mouseX + " Y:" + mouseY , mouseX + 35, mouseY + 40, 250)
// Draw when you need
function drawAgain () {
if (app.clearCanvas == true){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(mouseX, mouseY, 350, 65);
ctx.fillStyle = 'lime';
ctx.fillText(app.title + " X:" + mouseX + " Y:" + mouseY , mouseX + 35, mouseY + 40, 400)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cube Quest</title>
<style>
#game {
border: 1px dashed black;
}
</style>
</head>
<body>
<canvas id="game" width='1280' height='720'>Your browser does not support the canvas element in HTML5.</canvas>
<script>
</script>
</body>
</html>
Suggestion: Also learn to use removeEventListener , lot of web
developers have trouble with event conflict situation when they use
lot of lib's. For dynamic app flow methodology use removeEventListener
before setting a flags.
Having error in event.cilentX because event is not available at this moment so that is not moving to next lines of code to execute. If you want to play with event you need to attache any event listener like canvas.addEventListener('click' , function (event){//here you will get the event});. I just commented the two line now it working fine to draw rectangle.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cube Quest</title>
<style>
#game {
border: 1px dashed black;
}
</style>
</head>
<body>
<canvas id="game" width='1280' height='720'>Your browser does not support the canvas element in HTML5.</canvas>
<script>
var clicked = false; // Mouse handling event
// var mouseX = event.cilentX; // Mouse X coordinate
// var mouseY = event.cilentY; // Mouse Y coordinate
var canvas = document.getElementById("game"); // For canvas
var ctx = canvas.getContext("2d"); // For canvas
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(10, 10, 150, 80);
</script>
</body>
</html>
It's your mouse event listeners that are breaking the program.
Comment them out and it works just fine.
Here is a code snippet I use for small JavaScript games I test out.
//Mouse Events ==================
document.onmousemove = mousePos;
document.onmousedown = function() { mouse.clicked = true; };
document.onmouseup = function() { mouse.clicked = false; };
//MOUSE
var mouse = {
x: 0,
y: 0,
clicked: false
};
function mousePos (e) {
mouse.x = e.pageX - canvas.offsetLeft;
mouse.y = e.pageY - canvas.offsetTop;
}
I have a problem. I'm using HTML5 and Javascript to draw a box onto a canvas. This box is supposed to move up and down, but after it gets rendered for the first time, it doesn't want to re-render at the new position. This is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="sl" lang="sl">
<head>
<title>Spletna stran Portfolio - Domaca stran</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<script>
var isMoving = true;
var gradienty = 0;
var gradientheight = 100;
var gradientyVel = 1;
var gradientImage = new Image();
gradientImage.src = "grafika/gradient.gif";
function main() {
var c = document.getElementById("menuCanvas");
var ctx = c.getContext("2d");
ctx.drawImage(gradientImage, 0, gradienty);
if(isMoving == true) {
gradienty += gradientyVel;
if((gradienty+gradientheight)==c,height || gradienty<=0) {
gradientyVel *= -1;
}
}
}
function mainLoop() {
setInterval(main(), 10);
}
</script>
</head>
<body onload="mainLoop()">
<canvas id="menuCanvas" width="195" height="400"></canvas>
</body>
</html>
I have no clue why the box isn't moving. It's like after I draw it for the first time it won't draw again the next time. Also, I use mainLoop() function as my main loop. Every 10 miliseconds I basically call the main() function, which does the drawing and the logic.
Any help would be much appreciated. :)
A few coding problems:
You need to give your image time to load, then start the animation
var gradientImage = new Image();
gradientImage.onload=function(){
setInterval(main, 20);
}
gradientImage.src = "house16x16.png";
setInterval takes in a function pointer (no parentheses):
setInterval will fire only as fast as 16ms, so your 10ms value is too small
setInterval(main, 20);
Here's revised code and a Demo: http://jsfiddle.net/m1erickson/U6K9j/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var c=document.getElementById("menuCanvas");
var ctx=c.getContext("2d");
var isMoving = true;
var gradienty = 0;
var gradientheight = 100;
var gradientyVel = 1;
var gradientImage = new Image();
gradientImage.onload=function(){
setInterval(main, 20);
}
gradientImage.src = "house16x16.png";
function main() {
ctx.clearRect(0,0,c.width,c.height);
ctx.drawImage(gradientImage, 0, gradienty);
if(isMoving == true) {
gradienty += gradientyVel;
if((gradienty+gradientheight)==c.height || gradienty<=0) {
gradientyVel *= -1;
}
}
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="menuCanvas" width=300 height=300></canvas>
</body>
</html>
You're calling main and then passing the RESULT to setInterval. Just change
function mainLoop() {
setInterval(main(), 10);
}
to
function mainLoop() {
setInterval(main, 10);
}
That'll get you started, but you'll also need to clear the canvas in between draws. (As you'll notice if you run this)