I don't understand one things with js. If I have my .js file and in HTML I have following code:
<head>
<script src="skrypt.js"></script>
</head>
<body>
Content
</body>
Does it mean that during first execution my skrypt.js will be performed ?
Because When I have in my skrypt.js code :
document.write("HelloWorld")
Output is "HelloWorld" but when I have in skrypt.js :
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "red";
context.fillRect(0, 0, 300, 300);
Page is blank and I have to use event :
<body onload="drawCanvas();">
</body>
Where drawCanvas() has the same code like in external .js file.
So why document.write is working while canvas is not ???
JavaScript files loaded in the head are processed before the DOM is ready. You'll need to wrap your function in window.onload, call it elsewhere after the page loads, or put the external file call in at the bottom of your page document, just before the closing body tag.
Related
how to run this code in jsFiddle?
original code from Adam Khoury's site at http://www.developphp.com/view.php?tid=1262
I've experimented and am able to get the button to show and the canvas outline but can not get the object to animate from left to right when the button is clicked.
Here is my attempt to get it to run in jsFiddle at...
http://jsfiddle.net/Tn8xC/
function draw(x,y){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.clearRect(0,0,550,400);
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect (x, y, 50, 50);
ctx.restore();
x += 1;
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
Thanks for any help.
JSFiddle's default settings have JavaScript run onLoad, or after the HTML loads.
This works well for most cases, except for when you use an on* attribute to execute JS inline, because the JS hasn't loaded, so you can't access its variables and methods.
You need to change onLoadto No wrap - in <head> in the left sidebar at the top: this places your JS in <script> tags in the head. The head loads before everything else (whatever you put in the HTML area), so when you use the onclick attribute to reference your draw() function, it has already been defined.
You can also use No wrap - in <body> because the JS will still be placed before the rest of your HTML, but placing it in the head should serve you well in most cases.
Had you checked the console, you would have seen ReferenceError: Can't find variable: draw, which would have told you that your JS hadn't loaded before you tried to access draw().
Demo
I'm following this tutorial to learn HTML5 game development using javascript and jQuery. However, I've already come across a problem. When I run the HTML page that my js file is referenced from, nothing loads, and is just a blank screen. Here is the code for both files. Note that I haven't gotten very far in the tutorial.
index.html
<HTML>
<head>
</head>
<body>
<p>HTML5 and jQuery Tests</p>
<script type ="text/javascript" src="test.js"></script>
</body>
</HTML>
test.js
var CANVAS_WIDTH = 480;
var CANVAS_HEIGHT = 320;
var canvasElement = $("<canvas width='" + CANVAS_WIDTH +"' height='" + CANVAS_HEIGHT + "'></canvas>");
var canvas = canvasElement.get(0).getContext("2d");
canvasElement.appendTo('body');
var FPS = 30;
setInterval(function() {
update();
draw();
}, 1000/FPS);
function draw() {
canvas.fillStyle = "#000";
canvas.fillText("hello.", 50, 50);
}
Any help would be greatly appreciated! Also, am I allowed to ask questions about this code in this forum, on the same thread, or do I have to stat another?
Thanks!
~Carpetfizz
You don't have an update function to call. When the setInterval fires (which is ~32ms after the script loads), you're getting an error.
You need to add jQuery.
It's a library that was written to make working with HTML easier.
It needs to exist above where test.js does.
You can either download your own copy of it, or link to a copy elsewhere on the net - both will work fine.
$ is used by jQuery as a function to intelligently grab different kinds of items: HTML, JS, etc, and return JS objects with helpful functions for working with whatever you asked for.
Anyway, the update would still have caused an error, it was just second in line, behind the missing script.
I have been mucking about with a little bit coding using jquery and canvas (not together).
I have an external javascript file and in it contains;
$(document).ready(function() {
/*
NAME CHOOSER
*/
var carl = ['Sha', 'Shads', 'Cai', 'Moon', 'Sun', 'Staffy',];
var rosie = ['Mum',];
var prev;
$('button').click(function() {
prev = $('h2').text();
$('h2').empty().text(carl[Math.floor(Math.random() * carl.length)] + rosie[Math.floor(Math.random() * rosie.length)]).after('<p>' + prev + '</p>');
});
});
I also have some inline javascript which is for the canvas element;
<script>
var canvas = document.getElementById('draw');
if(canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 800, 500);
}
</script>
When separated by using inline javascript for the canvas and an external file for the jquery everything works fine and as expected.
When adding the inline canvas javascript to the external file the canvas element is not working but the jquery is. The javascript is loaded after the canvas element as my external javascript is linked just before the closing body tag and furthermore if I remove all jquery from the external file the canvas element begins to work again.
Why is this?
Thanks
EDIT
I have also now tried putting the canvas code inside jquerys document ready function and outside of it and it is still not working. I have wrapped the canvas code in an anonymous function still to no avail and have even tried selecting the canvas element with jquery itself like below;
var canvas = $('canvas')[0];
But it still doesn't want to know. Putting the canvas code before all the jquery then the canvas code executes but the jquery doesn't, I really am baffled! It doesn't bother me keeping it seperate but I would like to know why it is happening.
Thanks again.
This simple problems could be noted if you use the Browser Console. That's it! You can open the console pressing Ctrl+Shift+J:
In home page:
Error: Uncaught ReferenceError: $ is not defined
Solution: Link jQuery in your source
In namechooser page:
Error: Uncaught TypeError: Cannot read property 'getContext' of null
The problem:
You are trying to manipulate a div as it was a canvas, and you can't get the context of a div element. So this is your HTML:
<div id="wrap">
<h1>PORTFOLIO PROJECT :)</h1>
<button>Click here to generate a company name!</button>
</div>
Solution:
Change <div> for <canvas>
How to avoid future problems like this?
Use the browser console, that's it!
Ok, if I combine the code you have, above, it should look something like this: (see my jsFiddle for full context : http://jsfiddle.net/mori57/TqamB/ )
$(document).ready(function () {
/*
NAME CHOOSER
*/
var carl = ['Sha', 'Shads', 'Cai', 'Moon', 'Sun', 'Staffy'];
var rosie = ['Mum'];
var prev;
$('button').click(function () {
prev = $('h2').text();
$('h2').empty().text(carl[Math.floor(Math.random() * carl.length)] + rosie[Math.floor(Math.random() * rosie.length)]).after('<p>' + prev + '</p>');
});
var canvas = document.getElementById('draw');
if(canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 800, 500);
}
});
And, running within the context of jsFiddle, this works perfectly.
So, either you're not combining the two scripts properly (putting the canvas outside the document-ready block, for example, or somehow missing a closing brace), or there's something else amiss in your script file or markup.
I have written this code in JavaScript and works perfectly fine when I include it on my index.html page:
<canvas id="bannerCanvas" width="960" height="200">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("bannerCanvas");
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(25,25);
context.lineTo(355,55);
context.lineTo(355,125);
context.lineTo(25,125);
context.moveTo(465,25);
context.fill();
};
</script>
...however when I place it in an external JavaScript file, it won't work! In the head of the index page, I have declared this:
<script type="text/javascript" src="JavaScript/functionality.js">
</script>
And I save this functionality.js file in the JavaScript directory, I've tried doing other JS functions in this file to check the index page and the JS are connected and they are...The answer is probably staring me in the face but for some reason I cannot see it!
Any help is much appreciated, thank you.
EDIT: I've been using Firebug and it is giving me no errors, when I use the code on the index page, I am seeing the shape I want yet when using the external JS file I am just seeing a big black rectangle.
the reason for this is that the script is being run before the canvas element is rendered.
To fix it, add this in your external file.
document.addEventListener('DOMContentLoaded',domloaded,false);
function domloaded(){
// your code here.
}
or with jquery
$(function(){
// your code here.
});
Within functionality.js, try wrapping your code in
window.onload = function() {
// code here
}
so that it won't execute until after the page has loaded.
If it is in the head, you are loading it before the canvas element is rendered. Look at the JavaScript console and you will see a Null or undefined error.
Add the script tag in the same place it works with the inline code. JavaScript does not have to live in the head and some developers will recommend it should always be the last thing in the body.
Other solution is to run the script on document ready or window onload.
Dont put in the head, When you put the code in the head, it run the code when there is no canvas element in page yet.
I'm writing a webpage that relies on an external javascript file (that I have no control of), which returns data by using document.write's. Is there any way to dynamically call the function without it overwriting the whole document? Here's the most concise code I can think of:
<html>
<head>
<script type="text/javascript">
function horriblefunction () {
document.write("new text");
}
</script>
</head>
<body>
Starting Text...
<div id="pleasewriteinme"></div>
Other text...
<button onclick="horriblefunction();">Click</button>
</body>
</html>
The idea beginning that without altering "horriblefunction()" (as it's external) the new text could be placed in the div instead of overwriting the page. Is this possible or does the function have to be called inside the div as the page is created?
Thanks for you help
The only way to use document.write after the page has finished rendering is to temporarily replace the function with one of your own making that will shove the content into a div. E.g.
function horriblefunction() {
var old_dw = document.write;
document.write = function(text) {
document.getElementById( 'some_div' ).innerHTML = text;
}
// now call your external JS function that uses document.write
document.write = old_dw;
}
This will work as long as the external JS is already loaded and you're just calling a function. If you need to load the JS (say, by inserting a new <script> tag into the DOM) remember that that operation is asynchronous, and you'll need to watch the DOM to know when it's safe to restore the old version of document.write.
Try using dynamic script loading from http://bezen.org/javascript/index.html
bezen.domwrite.js - Captures document.write and writeln for the safe loading of external scripts after page load.