Cannot add canvas with external JS file - javascript

I am trying to add a canvas to my index.html but it's not working at all. As in it doesn't show up. Here is my index.html and game.js file source. Please help, I've been trying to figure this out for the last hour or so and it still doesn't work. I've tested it in multiple browsers. I'm using brackets as my editor if that helps.
index.html
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dogepet</title>
</head>
<body>
<center><p>Dogepet</p>
<script type="text/javascript" src="js/game.js"></script></center>
</body>
</html>
game.js
//Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 612;
canvas.height = 480;
document.body.appendChild(canvas);
//Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "images/dogepark.png";
var doge = {
speed: 10;
x: canvas.width/2;
y: 380;
};
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
};
var main = function () {
render();
};
setInterval(main,1);

Look into the Javascript console. In Firefox, I see this error message
[22:39:46.543] SyntaxError: missing } after property list
After replacing the semicolons ; with commas ,, everything works as expected.
See JSFiddle

Related

HTML to run JS image transform function

cutImageUp is a js script that's already been discussed in SE, here Shattering image using canvas. But I have a different question about using it. The html I try doesn't do anything. I'm sure that I've done a simple wrong, but I'm too much of a noob to see it.
The cutImageUp script:
<script type="text/javascript">
var image = new Image();
image.src = "letere.png"; image.onload = cutImageUp;
var imagePieces = [];
function cutImageUp() {
for(var x = 0; x < 5; x++) {
for(var y = 0; y < 5; y++) {
var canvas = document.createElement('canvas');
canvas.width = 50;
canvas.height = 50;
var context = canvas.getContext('2d');
context.drawImage(image, x *50, y * 50, 50, 50, 0, 0, 50, 50);
imagePieces.push(canvas.toDataURL());
}
}
var anImageElement = document.getElementById('img');
anImageElement.src = imagePieces[0];
}
</script>
My html:
<html>
<head>
<script src="cutImageUp.js"></script>
</head>
<body>
<img src="letere.png" onload="cutImageUp()" width="50" height="50">
</img>
</body>
</html>
When I run the page, the image appears, without the function applied. I might as well run the page without js. BTW, the files are in the same folder, and I tried using Base64, no luck.
Remove the <script> tags around the JavaScript code in cutImageUp.js. You only need those when you embed JS code in an HTML file.

I am getting "Uncaught TypeError: Cannot read property 'width' of null" after following a tutorial

This is my javascript code, but nothing seems wrong too me. My html id is not wrong either. I was following a tutorial on youtube and it worked for the person that did it. Can anyone help me with this?
var canvas;
var ctx;
var background;
var width = 300;
var height = 200;
var cloud;
var cloud_x;
function init() {
canvas = document.getElementById("mycanvas");
width = canvas.width; //THIS IS WHERE I GET MY ERROR
height = canvas.height;
ctx = canvas.getContext("2d");
// init background
background = new Image();
background.src = 'http://silveiraneto.net/wp-content/uploads/2011/06/forest.png';
// init cloud
cloud = new Image();
cloud.src = 'http://silveiraneto.net/wp-content/uploads/2011/06/cloud.png';
cloud.onload = function(){
cloud_x = -cloud.width;
};
return setInterval(main_loop, 10);
}
function update(){
cloud_x += 0.3;
if (cloud_x > width ) {
cloud_x = -cloud.width;
}
}
function draw() {
ctx.drawImage(background,0,0);
ctx.drawImage(cloud, cloud_x, 0);
}
function main_loop() {
draw();
update();
}
init();
My html
<canvas id="mycanvas" width="640" height="480">Alternative text if browser don't support canvas.</canvas>
Change this line:
init();
By this line:
document.addEventListener('DOMContentLoaded', init, false);
The init function will be called when the DOM is ready.
jsfiddle

JavaScript runtime error: Unspecified error

My requirement is to return data URL. But, when I run the application, there is an run-time error:
JavaScript runtime error: Unspecified error.
Here is the code that I have used. Temp path is the path where is location of image is.
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var img = new Image();
img.src = "#tempPath";
context.drawImage(img, 40, 40);
var dataURL = canvas.toDataURL("image/jpeg");
alert(dataURL);'
Try following code, It worked for me:
<body>
<canvas id="myCanvas"></canvas>
<img id="profileImg" alt=""/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
drawImg();
});
function drawImg() {
try {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var img = new Image();
img.src = $('#profileImg');
context.drawImage(img, 40, 40);
var dataURL = canvas.toDataURL("image/jpeg");
alert(dataURL);
} catch (e) {
if (e.name == "NS_ERROR_NOT_AVAILABLE") {
// This is a bug in Firefox. The easiest fix is to simply keep trying until the error goes away,
//since no event fires at the correct time.
// Wait before trying again; you can change the length of this delay.
setTimeout(drawImg, 100);
} else {
throw e;
}
}
}
</script>
</body>
Works well with IE as well. Hope this helps.

How to get the color of a pixel from image?

I want to get the color of a pixel from image with using pure JavaScript.
I wrote this script, but it did not work:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Get Pixel</title>
<script type='text/javascript'>
window.onload = function() {
var canvas = document.createElement("canvas");
var pic = new Image();
pic.src = 'http://i.imgur.com/hvGAPwJ.png';
pic.onload = function() {
canvas.width = pic.width;
canvas.height = pic.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(pic, 0, 0);}
var c = canvas.getContext('2d');
var p = c.getImageData(7, 7, 1, 1).data;
var hex = "RGB = " + p[0]+", "+p[1]+", "+p[2];
document.getElementById("output").innerHTML = hex;
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
How to change the code, what would he worked correctly?
For example for the picture "http://i.imgur.com/hvGAPwJ.png", the result should be RGB = 255, 255, 255.
Your code is almost (see below) correct in its self BUT unfortunately when you use images from other origins than the page itself certain criteria must be there for it to work due to CORS (security feature).
You cannot use images from other origins out of the box. The server they are on need to have accept-* header set to allow this.
If not your getImageData and toDataURL will be blank (throws a security error that you can see in the console).
If you don't have access to modify the server the only way to get around this is to use your own server as a image proxy (http://myServer/getImage.cgi|php|aspx...?http/otherServer/img)
As pointed on in comments always set src after onload so you are sure onload gets initialized.
var pic = new Image();
pic.onload = function() { /* funky stuff here */ };
pic.src = 'http://i.imgur.com/hvGAPwJ.png'; //Last
If you indent your script properly, the error becomes more apparent:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Get Pixel</title>
<script type='text/javascript'>
window.onload = function() {
var canvas = document.createElement("canvas");
var pic = new Image();
pic.src = 'http://i.imgur.com/hvGAPwJ.png';
pic.onload = function() {
canvas.width = pic.width;
canvas.height = pic.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(pic, 0, 0);
}
var c = canvas.getContext('2d');
var p = c.getImageData(7, 7, 1, 1).data;
var hex = "RGB = " + p[0]+", "+p[1]+", "+p[2];
document.getElementById("output").innerHTML = hex;
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
You are setting a function on the image's load event, but not waiting for it to happen before you update the contents of the div.
You should move everything inside the pic.onload function, apart from setting the pic.src:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Get Pixel</title>
<script type='text/javascript'>
window.onload = function() {
var canvas = document.createElement("canvas");
var pic = new Image();
pic.onload = function() {
canvas.width = pic.width;
canvas.height = pic.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(pic, 0, 0);
var c = canvas.getContext('2d');
var p = c.getImageData(7, 7, 1, 1).data;
var hex = "RGB = " + p[0]+", "+p[1]+", "+p[2];
document.getElementById("output").innerHTML = hex;
}
pic.src = 'http://i.imgur.com/hvGAPwJ.png';
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
Now the problem is just cross origin restrictions.
To solve cross origins restrictions, you may add this line:
pic.crossOrigin = "Anonymous";
Right after defining pic var.
May not work in some cases though.

Using HTML5 Canvas to parse an image into a tileset

I'm attempting to parse a tileset image (of type .png) into an array. I've got a test canvas that I'm using to draw it to first, then I am extracting the image info from it. When I run this code, it throws "Uncaught TypeError: Type error." I was able to log that this.mainTiles is empty. Any ideas? I don't know all the subtleties of Canvas yet, so I'm stuck. Thanks for the help! (Also, you can ignore the last line at the end, I was just using it to test--but I wanted to illustrate that it doesn't work).
function TileSet() {
this.tileSheets = [];
this.mainTiles = [];
this.tileHeight = 32;
this.tileWidth = 32;
this.addSpriteSheet = function (spriteSheetLoc, name) {
var tileSheet = new Image();
try {
tileSheet.src = spriteSheetLoc;
}
catch(err) {
dMode.Log("Invalid TileSheet Src ( TileSet.setSpriteSheet() Failed ); ERR: " + err);
}
tempContext.drawImage(tileSheet, 0, 0);
var tilesX = tempContext.width / this.tileWidth;
var tilesY = tempContext.height / this.tileHeight;
for(var i=0; i<tilesY; i++) {
for(var j=0; j<tilesX; j++) {
// Store the image data of each tile in the array.
this.mainTiles.push(tempContext.getImageData(j*this.tileWidth, i*this.tileHeight, this.tileWidth, this.tileHeight));
}
}
context.putImageData(this.mainTiles[0], 5, 5);
}
Edit: Here are how the canvases and such are defined:
var tempCanvas = document.getElementById("tempCanvas");
var tempContext = tempCanvas.getContext("2d");
var canvas = document.getElementById("gameCanvas");
var context = canvas.getContext("2d");
var Tiles = new TileSet;
//this is the line it gets stuck at
Tiles.addSpriteSheet("resources/tiles/tilea2.png");
Edit 2: After markE's answer, here's the latest update. Still feel as though I'm missing a fundamental property regarding .onload.
function TileSet() {
this.Tiles = [];
this.tileHeight = 32;
this.tileWidth = 32;
this.tileCount = 4;
this.addSpriteSheet = function (spriteSheetLoc, name) {
var tileSheet = new Image();
tileSheet.onload = function() {
tempCanvas.width = tileSheet.width;
tempCanvas.height = tileSheet.height;
tempContext.drawImage(tileSheet, 0, 0);
for (var t=0;t<this.tileCount;t++) {
this.Tiles[t]=tempContext.getImageData(t*this.tileWidth,t*32,this.tileWidth,tileSheet.height);
dMode.Log(this.Tiles);
}
context.putImageData(this.Tiles[this.Tiles.length-1],0,0);
dMode.Log(this.Tiles);
}
tileSheet.src = spriteSheetLoc;
}
Here's how to parse a spritesheet into an array of separate canvas imageData
I have some working code that does what you want to do.
I didn't have your "resources/tiles/tilea2.png" so I used my own "monstersArun.png" which is a 10 across spritesheet of 64x64 tiles.
You can modify this code to fit your spritesheet layout ( rows x columns and tile size).
Here is the code:
<!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 canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var tileCount=10;
var tiles=new Array();
var tileWidth;
var t;
var img=new Image();
img.onload=function(){
canvas.width=img.width;
canvas.height=img.height;
tileWidth=img.width/tileCount;
ctx.drawImage(img,0,0);
for(var t=0;t<tileCount;t++){
tiles[t]=ctx.getImageData(t*tileWidth,0,tileWidth,img.height);
}
// just a test
// draw the last tiles[] into another canvas
var canvasTile=document.getElementById("canvasTile");
var ctxTile=canvasTile.getContext("2d");
canvasTile.width=tileWidth;
canvasTile.height=canvas.height;
ctxTile.putImageData(tiles[tiles.length-1],0,0);
}
img.src="monsterarun.png";
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas><br/>
<canvas id="canvasTile" width=64 height=64></canvas>
</body>
</html>
[Edit--to include Juan Mendes good idea give help on coding problem]
Also, as I look at your code...here:
tileSheet.src = spriteSheetLoc;
This causes your image to load. That loading takes time to do, so javascript starts loading the image, but it also immediately goes on to your next line of code. As a result, your code below tries to use the image before it's available--no good!
So you should give javascript a chance to fully load your image before processing the rest of your code. You do this using the onload method of Image like this:
var tileSheet = new Image();
tileSheet.onload=function(){
// put ALL you code that depends on the image being fully loaded here
}
tileSheet.src = spriteSheetLoc;
Notice how you put tileSheet.src after the onload function. In reality, javascript executes tilesheet.src and then goes back to execute all the code in the onload block!
[Edit again -- complete code]
<!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 tempCanvas = document.getElementById("tempCanvas");
var tempContext = tempCanvas.getContext("2d");
var canvas = document.getElementById("gameCanvas");
var context = canvas.getContext("2d");
// create a new TileSet
var Tiles = new TileSet();
// parse a spritesheet into tiles
//Tiles.addSpriteSheet("resources/tiles/tilea2.png","anyName");
Tiles.addSpriteSheet("houseIcon.png","anyName");
function TileSet() {
this.Tiles = [];
this.tileHeight = 32;
this.tileWidth = 32;
this.tileCount = 4;
this.addSpriteSheet = function (spriteSheetLoc, name) {
var me=this; // me==this==TileSet
var tileSheet = new Image();
tileSheet.onload = function() {
// calculate the rows/cols in the spritesheet
// tilesX=rows, tilesY=cols
var tilesX = tileSheet.width / me.tileWidth;
var tilesY = tileSheet.height / me.tileHeight;
// set the spritesheet canvas to spritesheet.png size
// then draw spritesheet.png into the canvas
tempCanvas.width = tileSheet.width;
tempCanvas.height = tileSheet.height;
tempContext.drawImage(tileSheet, 0, 0);
for(var i=0; i<tilesY; i++) {
for(var j=0; j<tilesX; j++) {
// Store the image data of each tile in the array.
me.Tiles.push(tempContext.getImageData(j*me.tileWidth, i*me.tileHeight, me.tileWidth, me.tileHeight));
}
}
// this is just a test
// display the last tile in a canvas
context.putImageData(me.Tiles[me.Tiles.length-1],0,0);
}
// load the spritesheet .png into tileSheet Image()
tileSheet.src = spriteSheetLoc;
}
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="tempCanvas" width=300 height=300></canvas><br/>
<canvas id="gameCanvas" width=300 height=300></canvas>
</body>
</html>
Try replacing tempContext.width and tempContext.height with tempCanvas.width and tempCanvas.height, respectively. I don't believe contexts have width/height.

Categories

Resources