Javascript not displaying in canvas - javascript

I've been creating a Flappy Bird game with JavaScript and for some reason, it's stopped displaying in the browser. I've checked the canvas displays by changing the background colour, but the actual JavaScript doesn't. I'm new to JavaScript, so I'm not sure where I'm going wrong. Thank you in advance.
Here is the html file:
<!DOCTYPE html>
<html>
<head>
<title>Flappy Bird using JS</title>
</head>
<body>
<canvas id="canvas" width="288" height="512"></canvas>
<script src="flappyBird.js"></script>
</body>
</html>
And here is the JS:
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
// load images
var bird = new Image();
var bg = new Image();
var fg = new Image();
var pipeNorth = new Image();
var pipeSouth = new Image();
bird.src = "images/bird.png";
bg.src = "images/bg.png";
fg.src = "images/fg.png";
pipeNorth.src = "images/pipeNorth.png";
pipeSouth.src = "images/pipeSouth.png";
// some variables
var gap = 85;
var constant = pipeNorth.height+gap;
var bX = 10;
var bY = 150;
var gravity = 1.5;
// on key down
document.addEventListener("keydown",moveUp);
function moveUp(){
bY -= 25;
}
// pipe coordinates
var pipe = [];
pipe[0] = {
x : cvs.width;
y : 0;
}
// draw images
function draw(){
ctx.drawImage(bg,0,0);
for(var i = 0; i < pipe.length; i++){
ctx.drawImage(pipeNorth,pipe[i].x,pipe[i].y);
ctx.drawImage(pipeSouth,pipe[i].x,pipe[i].y+constant);
pipe[i].x--;
if(pipe[i].x == 125){
pipe.push({
x : cvs.width,
y : Math.floor(Math.random()*pipeNorth.height) - pipeNorth.height
});
}
// detect collision
if(bX + bird.width >= pipe[i].x && bX <= pipe[i].x + pipeNorth.width &&
(bY <= pipe[i].y + pipeNorth.height || bY+bird.height >= pipe[i].y+constant)
|| bY + bird.height >= cvs.height - fg.height){
location.reload();
}
if(pipe[i].x == 5){
score++;
}
}
ctx.drawImage(fg,0,cvs.height - fg.height);
ctx.drawImage(bird,bX,bY);
bY += gravity;
ctx.fillStyle = "#000";
ctx.font = "20px Verdana";
ctx.fillText("Score: "+score,10,cvs.height-20);
requestAnimationFrame(draw);
}
draw();

Related

Html canvas flickering while stroking lines

<html>
<head>
<meta name="viewport" content="width=device-width">
<style>
body{
margin:0;
}
img{
display:none;
}
</style>
</head>
<body onload="Start()">
<canvas id="canvas"></canvas>
<img id="mapImg" src="Img/map.png"/>
<script>
var worker = new Worker("WebWorker.js");
var W = window.innerWidth;
var H = window.innerHeight;
var map = document.getElementById("mapImg");
var cvs = document.getElementById("canvas");
cvs.width = W;
cvs.height = H;
var ctx = cvs.getContext("2d");
var offscreenCvs = document.createElement("canvas");
offscreenCvs.width = W;
offscreenCvs.height = H;
var offscreenCtx = offscreenCvs.getContext("2d");
var mapCvs = document.createElement("canvas");
var mapCtx,mapData;
var px=25;
var py=0;
var pz=27;
var yaw=0;
var pitch=0;
var buffer=[];
function Start(){
mapCvs.width = map.width;
mapCvs.height = map.height;
mapCtx = mapCvs.getContext("2d");
mapCtx.drawImage(map,0,0);
mapData = mapCtx.getImageData(0,0,map.width,map.height);
worker.postMessage([px,py,pz,yaw,pitch,mapData]);
}
var delta = 0;
var dt = 0;
var Updated=false;
worker.onmessage = function(e){
dt = (performance.now()-delta)/1000;
buffer = e.data;
yaw+= dt*90;
if(!Updated){
requestAnimationFrame(Update);
Updated = true;
}
delta = performance.now();
worker.postMessage([px,py,pz,yaw,pitch,mapData]);
}
function Update(){
offscreenCtx.lineWidth = W/80;
var currentBuffer = buffer;
for(var dists=0; dists<80; dists++){
offscreenCtx.strokeStyle = currentBuffer[dists][0];
offscreenCtx.beginPath();
offscreenCtx.moveTo(W/80*dists,H/2-200/currentBuffer[dists][1]*H);
offscreenCtx.lineTo(W/80*dists,H/2+200/currentBuffer[dists][1]*H);
offscreenCtx.closePath();
offscreenCtx.stroke();
}
//alert(currentBuffer[60][0]);
/*offscreenCtx.strokeStyle = "rgb(255,0,0)";
offscreenCtx.beginPath();
offscreenCtx.moveTo(0,0);
offscreenCtx.lineTo(100,100);
offscreenCtx.stroke();*/
ctx.clearRect(0,0,W,H);
ctx.drawImage(offscreenCvs,0,0);
offscreenCtx.clearRect(0,0,W,H);
requestAnimationFrame(Update);
}
</script>
</body>
</html>
I'm trying to make a raycaster with color.
However, when I try to stroke lines, some lines flicker or invisible.
(red flickers,yellow is insivible)
(offscreenCtx.beginPath()
and
offscreenCtx.stroke()
is in for loop in order to change colors.)
here's my web-worker code
onmessage=function(e){
var pkg = e.data;
postMessage(Raycast(pkg[0],pkg[1],pkg[2],pkg[3],pkg[4],pkg[5]));
}
var far = 100;
function Raycast(x,y,z,yaw,pitch,mapData){
var distances=[];
var map = mapData.data;
for(var rayYaw = yaw-40;rayYaw<yaw+40;rayYaw++){
for(var l = 0;l<far;l+=1){
fx = x+Math.round(Math.sin(rayYaw/180*Math.PI)*l);
fz = z+Math.round(Math.cos(rayYaw/180*Math.PI)*l);
if(fx<0||fx>mapData.width||fz<0||fz>mapData.height){
let color = "rgb(255,255,255)";
distances.unshift([color,Math.min(Math.hypot(fx-x,fz-z),far)*100*Math.cos((rayYaw-yaw)/180*Math.PI)]);
break;
}else if(map[Math.round(fx+fz*mapData.width)*4]!=255&&map[Math.round(fx+fz*mapData.width)*4+2]!=255&&map[Math.round(fx+fz*mapData.width)*4+2]!=255){
let color = "rgb("+map[Math.round(fx+fz*mapData.width)*4]+","+map[Math.round(fx+fz*mapData.width)*4+1]+","+map[Math.round(fx+fz*mapData.width)*4+2]+")";
distances.unshift([color,Math.min(Math.hypot(fx-x,fz-z),far)*100*Math.cos((rayYaw-yaw)/180*Math.PI)]);
break;
}
}
}
return distances;
}
map.png
Is there anyone who can tell me what's wrong?

passing image src to onclick

I am executing the following script in order to convert an image into grayscale using Javascript.
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
<script>
function drawImage(imageObj) {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = 69;
var y = 50;
context.drawImage(imageObj, x, y);
var imageData = context.getImageData(x, y, imageObj.width, imageObj.height);
var data = imageData.data;
for(var i = 0; i < data.length; i += 4) {
var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
// red
data[i] = brightness;
// green
data[i + 1] = brightness;
// blue
data[i + 2] = brightness;
}
// overwrite original image
context.putImageData(imageData, x, y);
}
var imageObj = new Image();
imageObj.onload = function() {
drawImage(this);
};
imageObj.src = 'text.png';
</script>
Whenever i change the imageObj.src, my browser displays the indicated image in grayscale. However, what I want is to only display the converted image when i click on some sort of button. Given that my image was uploaded at the beginning of the script.
I tried
<button onclick="drawimage(uploadedFile)">Here</button>
It ovbiously didn't work.
I also want to use the new converted image in the rest of my code (store it in some sort of variable) and still couldnt figure out a way to do it.
Thank you for helping me out !
Try this,
Here is a live version https://jsbin.com/relokugumo/1/edit?html,js,output
Html To
<canvas id="myCanvas" width="578" height="400"></canvas>
<button onclick="setImage('<?php echo $uploadefile ?>')">Here</button>
And JS To,
function setImage(imagePath){
var imageObj = new Image();
imageObj.src = imagePath;
drawImage(imageObj);
}
function drawImage(imageObj) {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = 69;
var y = 50;
context.drawImage(imageObj, x, y);
var imageData = context.getImageData(x, y, imageObj.width, imageObj.height);
var data = imageData.data;
for(var i = 0; i < data.length; i += 4) {
var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
// red
data[i] = brightness;
// green
data[i + 1] = brightness;
// blue
data[i + 2] = brightness;
}
// overwrite original image
context.putImageData(imageData, x, y);
}
the onload() doesn't fire because the image is never loaded. you should do an ajax request to load the image and use your function in callback
This is what I use. Hope this helps.
<html>
<head>
<title>Canvas</title>
</head>
<body>
<input id="upload_file" type="file">
<button id="convert_button" onclick="convert()">Convert</button>
<a onclick="downloadimage(this)">Download image</a>
<script>
var upload_file_input = document.getElementById("upload_file");
upload_file_input.addEventListener("change",upload);
var bodyelem = document.getElementsByTagName("body")[0];
var canvas = document.createElement("canvas");
canvas.setAttribute("id","main_canvas");
var context = canvas.getContext("2d");
function upload(e)
{
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
var canvaselem = document.getElementById("main_canvas");
canvaselem && bodyelem.removeChild(canvaselem);
bodyelem.appendChild(canvas);
}
function convert()
{
var imagedata = context.getImageData(0,0,canvas.width,canvas.height);
var data = imagedata.data;
for(var i = 0,n=data.length;i<n;i+=4)
{
var average = data[i]*0.3 +data[i+1]*0.59 + data[i+2]*0.11;
data[i] = data [i+1] = data[i+2] = average;
}
context.putImageData(imagedata,0,0,0,0,imagedata.width,imagedata.height);
}
function downloadimage(elem)
{
var image = canvas.toDataURL();
elem.href = image;
var imagename = prompt("Name : ","");
elem.download = imagename ? imagename : "image" + ".png";
}
</script>
</body>
</html>

Image not showing up on canvas onload

I'm trying to make a player image move around on a canvas. The player image doesn't show up on load. I used an alert to check the onload and it does seem to be running but the image is not displayed.
The player image does not show up if I only move left and right, and it does not show up if I only move up and down. The image does show up after I have moved in both the X and Y directions which makes me think that the X and Y are not correctly set until my animation function sets them. I can't see what is wrong with the initial X and Y onload though I'm using my own images on my computer but I just plugged in some random pictures so you guys could see something load.
I just put the whole code on here I don't know if that is too much but I'm not sure what I did wrong. I'm very new at this and this is my first time posting a question on here. I would appreciate if someone tells me what I'm doing wrong.
edit: I changed
var destX = xToCenter;
var destY = yToCenter;
to just the actual numbers
var destX = 260;
var destY = 220;
and that works but I don't really understand why. Can someone explain why I can't use xToCenter and yToCenter for onload but it works during the movement function?
here is my jsfiddle
//create canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 600;
//create background canvas
var worldCanvas = document.getElementById("worldCanvas");
var wctx = worldCanvas.getContext('2d');
worldCanvas.width = 600;
worldCanvas.height = 600;
//player image
var avatar = new Image();
var sourceX = 32;
var sourceY = 32;
var sourceWidth = 16;
var sourceHeight = 32;
var destWidth = sourceWidth * 5;
var destHeight = sourceHeight * 5;
var destX = xToCenter;
var destY = yToCenter;
var speed = 4;
var faceRight = 0;
var faceLeft = 1;
var faceDown = 2;
var faceUp = 3;
var animation = [0, 32, 64];
var i = 0;
//background image
var worldMap = new Image();
var sMapX = 0;
var sMapY = 0;
var sMapWidth = canvas.width;
var sMapHeight = canvas.height;
var dMapX = 0;
var dMapY = 0;
var dMapWidth = canvas.width;
var dMapHeight = canvas.height;
var worldWidth = 1280;
var worldHeight = 873;
//center player
var xToCenter = (0.5 * dMapWidth - 0.5 * destWidth);
var yToCenter = (0.5 * dMapHeight - 0.5 * destHeight);
//load and draw background
worldMap.src = "http://img06.deviantart.net/75db/i/2013/332/5/2/random_background_by_electriczerox-d6vyp1u.png";
worldMap.onload = function() {
wctx.drawImage(worldMap, sMapX, sMapY, sMapWidth, sMapHeight, dMapX, dMapY, dMapWidth, dMapHeight);
alert("worldMap loaded");
}
//load and draw avatar
avatar.src = "http://www.somerandomfacts.com/wp-content/uploads/2013/11/jpg1";
avatar.onload = function() {
ctx.drawImage(avatar, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
alert("avatar loaded");
}
//clear and redraw
;
(function() {
function main() {
window.requestAnimationFrame(main);
wctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.clearRect(0, 0, canvas.width, canvas.height);
wctx.drawImage(worldMap, sMapX, sMapY, sMapWidth, sMapHeight, dMapX, dMapY, dMapWidth, dMapHeight);
ctx.drawImage(avatar, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
}
main();
})();
//move avatar
window.addEventListener('keydown', function(event) {
var keyPressed = event.keyCode;
switch (keyPressed) {
//a moves left
case 65:
if (sMapX > 0) sMapX -= speed;
destX = xToCenter;
sourceX = faceLeft * sourceWidth;
animationLoop();
sourceY = animation[i];
break;
//w moves up
case 87:
if (sMapY > 0) sMapY -= speed;
destY = yToCenter;
sourceX = faceUp * sourceWidth;
animationLoop();
sourceY = animation[i];
break;
//d moves right
case 68:
if (sMapX < worldWidth - dMapWidth) sMapX += speed;
destX = xToCenter;
sourceX = faceRight * sourceWidth;
animationLoop();
sourceY = animation[i];
break;
//s moves down
case 83:
if (sMapY < worldHeight - dMapHeight) sMapY += speed;
destY = yToCenter;
sourceX = faceDown * sourceWidth;
animationLoop();
sourceY = animation[i];
break;
}
});
//animate while moving
function animationLoop() {
window.requestAnimationFrame(changeI);
}
function changeI() {
if (i <= animation.length) i += 1;
animation[i];
if (i == animation.length) i = 0;
}
.canvas {
border: 1px solid;
position: fixed;
top: 0;
left: 0;
}
.worldCanvas {
border: 1px solid;
z-index: -1;
position: fixed;
top: 0;
left: 0;
}
<canvas class="canvas" id="canvas"></canvas>
<canvas class="worldCanvas" id="worldCanvas"></canvas>
I'm still learning but I think I can answer my own question. When I create a variable I should give it an initial value before I set it equal to another variable.

Keep track and display arrival order of array elements after animation ends in JavaScript

So, I have created an array of 10 blocks(rectangles) that move horizontally towards a "finish" line (end of canvas width) with variable speeds. I'm looking for a way to keep track of the arrival order of each array element and display it on top of each rectangle as it stops moving. I've tried using a counter and the fillText method to do that, but it only works until other elements come to a full stop and then it replaces the order. For a better view of what happens, here is my code. If anyone has any suggestions on what to use in order to fulfill my goal, it is very much appreciated. Keep in mind that I only use plain JavaScript as in no jQuery or other frameworks as I am learning the basics. Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cars</title>
<style>
canvas {
border:1px solid #3D0404;
}
h2 {
margin-left:23%;
}
</style>
<script>
var c;
var ctx;
var cars = [];
var width = 100;
var height = 100;
var x = 0;
var y = 0;
var i;
var temp;
var cw = 1000;
var ch = 1000;
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
function init() {
c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
pushCar();
}
function CreateCar(x,y,width,height,speed){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
}
function pushCar(){
for (var i=0; i<10; i++){
var speed = Math.random() * 10;
var car = new CreateCar(x,y,width,height,speed);
cars.push(car);
y += 100;
}
drawAll();
}
function clear (){
ctx.clearRect (0,0,cw,ch);
}
function draw(cars){
ctx.beginPath();
ctx.fillStyle = "#f00";
ctx.fillRect(temp.x, temp.y, width, height);
ctx.strokeStyle = "#000";
ctx.outlineWidth = 2;
ctx.strokeRect(temp.x, temp.y, width, height);
ctx.closePath();
}
function drawAll(){
clear();
var z = 1;
for (var i=0; i<cars.length; i++){
temp = cars[i];
draw(temp);
if (temp.x+100 < c.width){
temp.x += temp.speed;
}else {
ctx.font = "20pt Verdana";
ctx.fillStyle = "#000";
ctx.fillText(z, 950, temp.y+55);
z++;
}
}
requestAnimFrame(drawAll, c);
}
</script>
</head>
<body onLoad = "init()">
<canvas id="myCanvas" width="1000" height="1000"></canvas>
</body>
</html>
You need to put the z variable outside the loop, and save the position of each car in an object. You also need to check if position[i] is already defined to avoid incrementing the current position more times than needed.
var z;
var position;
function drawAll() {
clear();
for (var i = 0; i < cars.length; i++) {
temp = cars[i];
draw(temp);
if (temp.x + 100 < c.width) {
temp.x += temp.speed;
} else {
if (!position[i]) {
position[i] = z;
z++;
}
ctx.font = "20pt Verdana";
ctx.fillStyle = "#000";
ctx.fillText(position[i], 950, temp.y + 55);
}
}
requestAnimFrame(drawAll, c);
}
http://jsfiddle.net/acasaccia/u2vhaqyt/

How to make the objects fall in javascript?

I am trying to make this game, you should not collide the falling object. I have the objects falling and I have my black square, but it flashes when I run it and Im not sure how to make the code stop when the two objects collide together.
here is the code that I have so far!
<html>
<body>
<canvas id="canvasRegn" width="600" height="450"style="margin:100px;"></canvas>
<script>
var ctx;
var imgBg;
var imgDrops;
var noOfDrops = 50;
var fallingDrops = [];
function drawBackground(){
ctx.drawImage(imgBg, 0, 0); //Background
}
function draw() {
drawBackground();
for (var i=0; i< noOfDrops; i++)
{
ctx.drawImage (fallingDrops[i].image, fallingDrops[i].x, fallingDrops[i].y); //The rain drop
fallingDrops[i].y += fallingDrops[i].speed; //Set the falling speed
if (fallingDrops[i].y > 480) { //Repeat the raindrop when it falls out of view
fallingDrops[i].y = -25 //Account for the image size
fallingDrops[i].x = Math.random() * 800; //Make it appear randomly along the width
}
}
}
function setup() {
var canvas = document.getElementById('canvasRegn');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
imgBg = new Image();
imgBg.src = "http://www.hamdancommunications.com/HComm/img/wite%20square.png";
setInterval(draw, 36);
for (var i = 0; i < noOfDrops; i++) {
var fallingDr = new Object();
fallingDr["image"] = new Image();
fallingDr.image.src = 'http://s18.postimg.org/o6jpmdf9x/Line1.jpg';
fallingDr["x"] = Math.random() * 800;
fallingDr["y"] = Math.random() * 5;
fallingDr["speed"] = 3 + Math.random() * 5;
fallingDrops.push(fallingDr);
anotherGame();
}
}
}
setup();
function anotherGame(){
var canvas = document.getElementById("canvasRegn");
var ctx = canvas.getContext('2d');
canvas.addEventListener("mousedown", clicked);
canvas.addEventListener("mousemove", moved);
canvas.addEventListener("mouseup", released);
var isclicked = 0;
var square = new Object();
square.color = "black";
square.x = 100;
square.y = 100;
square.w = 50;
square.h = 50;
var offX = 0;
var offY = 0;
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = square.color;
ctx.fillRect(square.x,square.y,square.w,square.h);
}
function game(){
}
function clicked(e){
var x = e.offsetX;
var y = e.offsetY;
if(x >= square.x && x <= square.x + square.w &&
y >= square.y && y <= square.y + square.h){
isclicked = 1;
offX = x - square.x;
offY = y - square.y;
}
}
function moved(e){
if(isclicked == 1){
var x = e.offsetX;
var y = e.offsetY;
square.x = x - offX;
square.y = y - offY;
}
}
function released(e){
var x = e.offsetX;
var y = e.offsetY;
isclicked = 0;
}
var drawtimer = setInterval(draw, 1000/30);
var gametimer = setInterval(game, 1000/10);
}
</script>
</body>
</html>

Categories

Resources