Please, may someone help me! I am new in javascript.
I want to make canvas animation using javascript. But I have the following error
SCRIPT5007: Unable to get value of the property 'getContext': object
is null or undefined drawing_script.js, line 31 character 5
Here is the code.
Javascript:
// JScript source code
/*
Because the canvas can hold only one context at time, we'll create two canvas. Each one with its context.
One canvas for the circle, and another one for the square.
*/
var canvasCircle;
var contextCircle;
var x = 400;
var y = 300;
var dx = 2;
var WIDTH = 800;
var HEIGHT = 600;
// the circle wont make any transsformation.
function draw_circle(x, y, r) {
contextCircle.beginPath();
contextCircle.arc(x, y, r, 0, 2 * Math.PI, true);
contextCircle.closePath();
contextCircle.stroke();
}
function clear_canvas() {
contextCircle.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
//canvasCircle = document.getElementById("canvas_circle");
canvasCircle = document.getElementById("canvas_circle");
contextCircle = canvasCircle.getContext('2d');
return setInterval(draw, 10);
}
function draw() {
// clear_canvas();
draw_circle(x, y, 50);
// if (x + dx > WIDTH || x + dx < 0)
// dx = -dx;
// x += dx;
}
init();
HTML5:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="Scripts/drawing_script.js" language="javascript"></script>
<title>Blackberry</title>
</head>
<body>
<div class="drawing" style="background:Green">
<canvas id="canvas_circle" width="800" height="600"></canvas>
This is happening because your executing the script before you create the canvas.
Create the canvas element FIRST then embed the javascript.
IE: canvasCircle is undefined because you can't get an element by ID that does not exist yet!
I found the answer: the init() should be
function init() {
s_canvas = document.getElementById("canvas_square");
// Check if the canvas is supported and if the getContext is available
if (s_canvas && s_canvas.getContext) {
s_context = s_canvas.getContext("2d");
return setInterval(draw, 10);
}
else {
alert("Canvas is not supported!");
}
}
And the called of init() is replace with window.onload=init.
Since you said that you are new to javascript, I believe that the problem could be that the browser on which you are running the code may not be supporting canvas.
Related
I have a working getContext in my JavaScript code, but for some reason nothing is executed after this method. Here, I added two alerts and only one of them runs:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas"
width="0"
height="0"
style="border:5px solid #888888; fill: solid #DDDDDD;"
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
// basic vars
var squareDim = 25;
var screenWidth = 10;
var screenHeight = 20;
// setting up the canvas
var canvas = document.getElementById("myCanvas");
canvas.width = screenWidth * squareDim;
canvas.height = screenHeight * squareDim;
alert(1)
var ctx = c.getContext("2d");
alert(2);
// draw a single square
function putSquare(color, x, y) {
ctx.fillStyle = color;
ctx.fillRect(x * squareDim, y * squareDim, squareDim, squareDim);
}
for (i=0; i<screenHeight; i++) {
putSquare("#FF0000", i, 0);
}
</script>
</body>
Does anyone have an idea where did I screw up?
You're calling c.getContext(...), you have no c variable declared - you need to call this on canvas instead:
var ctx = canvas.getContext('2d');
In future you can debug things like this in your browser's JavaScript console. In your JavaScript console, you'll see that your code here is throwing the following error:
Uncaught ReferenceError: c is not defined
See: How to open the JavaScript console in different browsers?
I want to make a loading bar for my web application and I want to use a html canvas for this. This is the script that I use to fill up the canvas:
<script>
var canvas = document.getElementById("bar");
var c = canvas.getContext("2d");
var xPos = 0;
draw = function() {
if(xPos < 300){
c.rect(0, 0, xPos, 30);
c.fill(255,0,0);
xPos += 0.5;
}
};
</script>
I tested this code on a online code converter (khan academy) and it worked (of course without the first 2 lines and c. in front of most things), and that is also my trouble I don't know where I have to put c. in front of?
I simplified the page a little bit:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
<canvas id="bar"></canvas>
<script>
var canvas = document.getElementById("bar");
var c = canvas.getContext("2d");
c.fillStyle = "#ff0000"
draw = function(){
if(xPos < 300){
c.fillRect(0, 0, xPos, 30);
xPos += 0.5;
}
};
</script>
</body>
</html>
Whatever you are trying to draw... this:
draw = function(){
if(xPos < 300) {
c.fillRect(0, 0, xPos, 30);
xPos += 0.5;
}
};
... it is a definition of variable in global context (context of window object), then assigning a function to it. That's all - it only defines the behavior.
What you need also needs to execute that (a sidenote: to execute it after the canvas is actually created - when you put code in a script tag after canvas tag - it's sufficient and you did it already).
To execute the function use:
draw();
Or don't wrap code in function at all (unless it's to be called multiple times).
Or use a syntax construct to execute the function created in place like this:
(draw = function(){
if(xPos < 300) {
c.fillRect(0, 0, xPos, 30);
xPos += 0.5;
setTimeout(draw,15); // use this to achieve animation effect
}
})();
var xPos = 0;
var canvas = document.getElementById("bar");
var c = canvas.getContext("2d");
c.fillStyle = "#FF0000";
var draw;
(draw = function(){
if(xPos < 300) {
c.fillRect(0, 0, xPos, 30);
xPos += 0.5;
setTimeout(draw,15);
}
})();
#bar {
width: 300px;
height: 50px;
}
<canvas id="bar"></canvas>
Edit: I've been thinking of what you might need, as it's not entirely abvious what you want. I have created this jsfiddle. Maybe it'll be of any help.
Hmmm...
You got some things mixed up. Try this:
<html>
<canvas id = "cvs1" width = "300" height = "30"></canvas>
</html>
And for the script:
var c = document.getElementById("cvs1").getContext("2d");
c.fillStyle = "#ff0000" //Set Fill Color(Set to red)
if(xPos < 300){
c.fillRect(xPos, 0, 30, 30);
xPos += 0.5;
}
If not:
What you did was use fill and rect seperately. You need to set the color, and then use the fillRect() function to draw the rectangle.
EDIT: You got the x,y,width,height as width,height,x,y. Fixed answer.
Good luck!
You need to call draw for every animation step. You could do this using setTimeout, setInterval or requestAnimationFrame :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
<canvas id="bar"></canvas>
<script>
var canvas = document.getElementById("bar");
var c = canvas.getContext("2d");
c.fillStyle = "#ff0000";
xPos=0;
draw = function(){
if(xPos < 300){
c.fillRect(0, 0, xPos, 30);
xPos += 0.5;
requestAnimationFrame(draw);
}
};
requestAnimationFrame(draw);
</script>
</body>
</html>
I've found a simple JavaScript bouncing ball animation, it works on chrome browser (PC)
When I run it, using Phonegap eclipse android emulator it compiles but canvas is blank and the following message displayed "unfortunately system ui has stopped"
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
<script>
var context;
var x = 100;
var y = 100;
var radius = 20;
var dx = 5;
var dy = 5;
function init(){
context = myCanvas.getContext('2d');
//Set an interval for the canvas to be refreshed.
// Basically call the draw function every 10 ms
setInterval(draw, 10);
}
function draw(){
//Clear the old circle before we draw the new one
context.clearRect(0,0, myCanvas.width, myCanvas.height); //This erases the entire canvas
context.beginPath();
context.fillStyle = "#0000ff";
//Draw a circle of radius 20 at the current coordinates on the canvas.
context.arc(x, y, radius, 0, Math.PI*2, true);
context.closePath();
context.fill();
//Check boundaries and negate if necessary
if (x + radius <= 0 || x - radius <= 0 || x + radius >= myCanvas.width || x - radius >= myCanvas.width)
dx = -dx;
if (y + radius <= 0 || y - radius <= 0 || y + radius >= myCanvas.height || y - radius >= myCanvas.height)
dy = -dy;
//Increment dx,dy
x+=dx;
y+=dy;
}
</script>
<title>Ball Bouncing</title>
</head>
<body onLoad = "init();"> <!-- when the body is loaded, call the init() function -->
<canvas id = "myCanvas" width ="500" height = "400">
</canvas>
</body>
</html>
Also for some reason it works if i remove the following:
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
ok so i removed
<body onLoad = "init();">
and added
document.addEventListener("deviceready",init,false);
and i get the following logcat:
09-23 21:53:30.886: E/Web Console(796): Uncaught SyntaxError: "Unexpected token < at file:///android_asset/www/index.html:7" whats is wrong ?
please help
Update
<script type="text/javascript" charset="utf-8">
<script>
var context;
Maybe the second script-tag is causing the problem?
There is a line missing like:
myCanvas = document.getElementById("myCanvas");
The html-canvas element should work fine with android. Try the "standard" browser from the android device (not chrome) and test the URL. Cordova uses this browserengine and not chrome.
If that works it is probabaly the app-initialization.
Don't use onLoad() in a caordova application. Before you do anything you have to wait for deviceready-event.
In your init() register for documenready and start your draw-timer within that event-handler.
Something different:
Use requestAnimationFrame() it is better for mobile devices, because you wull only repaint within the default paint-loop. Also only paint if needed (maybe if currently touched), you will suck the battery empty, if you always repaint.
I am asked to develop an application that will run on Blackberry. But I don't knowledge in java. Since the application needs drawing, I opt for html5 and javascript. Then I read some javascript tutorials. But when I try to put it into practice it, I get error saying that the "getContext" attribut is undefined.
Is it possible to write it in c#?
var canvasCircle;
var contextCircle;
var x = 400;
var y = 300;
var dx = 2;
var WIDTH = 800;
var HEIGHT = 600;
// the circle wont make any transsformation.
function draw_circle(x, y, r) {
contextCircle.beginPath();
contextCircle.arc(x, y, r, 0, 2 * Math.PI, true);
contextCircle.closePath();
contextCircle.stroke();
}
function clear_canvas() {
contextCircle.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvasCircle = document.getElementById("canvas_circle");
contextCircle = canvasCircle.getContext('2d');
return setInterval(draw, 10);
}
function draw() {
clear_canvas();
draw_circle(x, y, 50);
if (x + dx > WIDTH || x + dx < 0)
dx = -dx;
x += dx;
}
init();
<canvas id="canvas_circle" width="800" height="600"></canvas>
I'm not familiar with the Blackberry browser you are using, but it looks like it doesn't support Canvas. Dive Into HTML5 has a great chapter on feature detection: http://diveintohtml5.ep.io/detect.html
It also has a nice library called Modernizr you can use to detect HTML5 features. But to check for canvas support is pretty simple (as the chapter shows):
function supports_canvas() {
return !!document.createElement('canvas').getContext;
}
Ok so I don't understand why Firefox is saying that the $("#canvas")[0].getContext('2d'); is undefined. I put it out of the function so that all of the function can access it but here the ctx is still undefined.
(function($) {
// Undefined
var ctx = $('#canvas')[0].getContext("2d");
var x = 150;
var y = 150;
var dx = 2;
var dy = 4;
$(function() {
setInterval(draw, 10);
})
function draw() {
ctx.clearRect(0,0,300,300);
ctx.beginPath();
ctx.arc(x,y,10,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
x+=dx;
y+=dy;
}
})(jQuery);
However when I transferred the location of ctx to the unnamed function, the ctx is not undefined:
(function($) {
var ctx;
var x = 150;
var y = 150;
var dx = 2;
var dy = 4;
$(function() {
//Not Undefined
ctx = $("#canvas")[0].getContext('2d');
setInterval(draw, 10);
})
function draw() {
ctx.clearRect(0,0,300,300);
ctx.beginPath();
ctx.arc(x,y,10,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
x+=dx;
y+=dy;
}
})(jQuery);
Whats wrong with the first code? I mean var ctx is declared on the top. So that would make it a global variable. Hmm the error that I got was $("#canvas")[0] is undefined. Means that it can't access the #canvas.. Why??
I think you've mistaken the problem. It is not that you have misunderstood your variable context but probably that you are running the javascript before your canvas tag has been declared.
The following code demonstrates the problem. It will display the message "canvasOne is undefined!" because we are trying to access canvasOne before it is declared (Note the placement of the <canvas> tags).
I've created a hosted demo here: http://jsbin.com/afuju (Editable via http://jsbin.com/afuju/edit)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<script>
/*
The following line of code is run as soon as the browser sees it.
Since the "canvasOne" tag is not declared yet, the variable will be undefined.
*/
var canvasOne = $('#canvasOne')[0];
$(function() {
// The following code is run after the whole document has finished loading.
if (canvasOne === undefined) {
alert('canvasOne is undefined!');
}
else {
canvasOne.getContext("2d").fillRect(5, 5, 15, 15);
}
});
</script>
<canvas id="canvasOne"></canvas>
<canvas id="canvasTwo"></canvas>
<script>
/*
The following line of code is run as soon as the browser sees it.
But since the "canvasTwo" tag *is* declared above, the variable will *not* be undefined.
*/
var canvasTwo = $('#canvasTwo')[0];
$(function() {
// The following code is run after the whole document has finished loading.
if (canvasTwo === undefined) {
alert('canvasTwo is undefined!');
}
else {
canvasTwo.getContext("2d").fillRect(5, 5, 15, 15);
}
});
</script>
<script>
$(function() {
/*
The following code is run after the whole document has finished loading.
Hence, the variable will *not* be undefined even though the "canvasThree" tag appears after the code.
*/
var canvasThree = $('#canvasThree')[0];
if (canvasThree === undefined) {
alert('canvasThree is undefined!');
}
else {
canvasThree.getContext("2d").fillRect(5, 5, 15, 15);
}
});
</script>
<canvas id="canvasThree"></canvas>
</body>
</html>
This is because in your first call you're actually creating a Function object which will be processed only after the DOM has loaded, in another context.
That anonymous function will be called when all the elements in the page have already loaded, so the caller will be a jQuery core function and its context is completely different from the one you're coding here.
I'd suggest wrapping everything inside the $() call, so this should work:
(function($) {
$(function() {
var ctx = $("#canvas")[0].getContext('2d');
var x = 150;
var y = 150;
var dx = 2;
var dy = 4;
setInterval(draw, 10);
function draw() {
ctx.clearRect(0,0,300,300);
ctx.beginPath();
ctx.arc(x,y,10,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();
x+=dx;
y+=dy;
}
});
})(jQuery);