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
Related
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 5 years ago.
I started learning javascript after coding in java and c++ and I am trying to draw a rectangle. I can get a normal rectangle to draw If i just code normally in a script in the body but I wanna make my file look neat and have a function incase I need to call more rectangles in my program. I have googled around but I still can't figure out how to do this.
i have tried putting the function in the head section and my js file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PacMan</title>
<script scr="pac.js"></script>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//function drawRect(ctx, startX, startY, width, height, color){
//ctx.beginPath();
// ctx.rect(startX,startY,width,height);
// ctx.fillStyle = color;
// ctx.closePath();
// }
</script>
</head>
<body>
<canvas id="canvas" width="1000" height="720"></canvas>
<script>
drawRect(ctx,10,10,10,10, "#FF0000");
// this works but i can not get the function to work
//var canvas = document.getElementById("canvas");
//var ctx = canvas.getContext("2d");
//ctx.beginPath();
// ctx.rect(900, 10, 50, 50);
// ctx.fillStyle = "#FF0000";
//ctx.fill();
// ctx.closePath();
</script>
</body>
</html>
here is the .js file i created to try to keep my functions in a nice neat order so they do not clutter my files
function drawRect(ctx,h1,h2,w1,w2, color){
//i tired at one point putting this into function
//var canvas = document.getElementById("myCanvas");
// var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(20, 40, 50, 50);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
If I understood you correctly, you want to create a function that draws something and possibly be able to reuse that in other files?
Here's a working example to simulate a working function https://jsbin.com/puneseyuca/edit?html,js,output. You can also inspect the output area and check the DOM semantics.
There are a couple of things you should follow to make it work properly.
Put <script> just before </body>
<body>
<!-- DOM -->
// ...
<!-- Scripts -->
<script src="./path-to-your-js-file.js"></script>
</body>
Mostly you'll want to put your <script> files just before the ending body tag. Also, since you are not using any frameworks it would be good to be completely sure that the DOM is loaded, hence you could add this code:
document.addEventListener("DOMContentLoaded", function(event) {
// "DOM fully loaded and parsed"
// Insert your code here
});
This is important for the JS to be able to select elements from the DOM, otherwise they can be undefined.
Create a global variable, typically window.anything
⚠️ This should be avoided to avoid unexpected mutations and hence bugs
I do not endorse this approach, but that's how some libraries work by namespacing to the global window object. Otherwise, the variables set in 1 file are scoped to it i.e. cannot be accessed from outside.
So to do so you would declare a function and then save it to the global object i.e.
Inside e.g. duck.js
window.drawDuck = drawDuck
N.B. Be sure to check the order of your javascript files. A file declaring a global variable should come before the ones using it.
All said and done, I believe you can do what you intend to without global variables.
Hope I answered your question.
Happy Coding!
I'm making an Android game, in HTML5 and Javascript, I am part of the way there, but have hit something that has stumped me, My JS file and my Html file were working together, to draw on the canvas etc, but now I'm trying to draw an image on the canvas, nothing is being displayed, I know the img function is being found, as, alert (img);, works so it's just lost on me. (currently this is copied from a book I was given at college, and it's identical, the JS has been verified in JSHint and passes, so I'm lost) also, please be quite simple, I'm pretty new to JS but have used html for a long time, and this just has to be a simple game for a college assignment.
My HTML code is
<canvas id="game" width="1024" height="600">Sorry, your browser does not support this</canvas>
and my JS is:
function init() {
var elem = document.getElementById('game');
var canvas = elem.getContext('2d');
var img = document.createElement('img');
img.setAttribute('src', 'http://www.minkbooks.com/content/snow.jpg');
img.addEventListener("load", function() {
canvas.drawImage(img, 20, 20);
alert(canvas);
});
}
addEventListener("load", init);
and here it is on JSfiddle: http://jsfiddle.net/xw8m7/
This answer is based on your jsfiddle. You are executing your javascript code as soon as it is loaded. Depending on where your code is located in the html, the canvas element might not be loaded yet, and that would prevent your code from loading the image into the canvas element, and you would still get the alert.
In JSFiddle, you need to set the option of running your code "onDomready". That means that the JavaScript won't run until everything has been loaded (your canvas element). After changing that in your jsfiddle, your function loaded the image into the canvas just fine.
Update:
Based on your comment about XDK, I found a bit of example code and modified it. Original source: https://software.intel.com/en-us/node/493117
document.addEventListener("intel.xdk.device.ready",function(){
init();
},false);
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.