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?
Related
I attempted to animate a sprite sheet using html and javascript to no avail. Here is my sprite sheet
Below is lines 36-59 of my code. I'm not getting any errors so I don't really know what's wrong. How do I fix/improve my code?
This is for a project I'm doing. I've tried using different methods I've found online but none really worked either. I've tried shifting the image as well.
<html>
<head>
<title>Tree Animation</title>
</head>
<body>
<canvas id='canvas'></canvas>
<script>
var canWidth = 400;
var canHeight = 100;
//position where the frame will be drawn
var x = 0;
var y = 0;
var srcX;
var srcY;
var sheetWidth = 230;
var sheetHeight = 79;
var frameCount = 5;
var width = sheetWidth/frameCount;
var height;
var currentFrame = 0;
var tree = new Image();
tree.src = "tree sprite.jpg"
var canvas = document.getElementById('canvas');
canvas.width = canWidth;
canvas.height = canHeight;
var ctx = canvas.getContext('2d');
function updateFrame(){
currentFrame = ++currentFrame%frameCount
srcX = currentFrame*width;
srcY = 0;
ctx.clearRect(x, y, width, height);
}
function draw(){
updateFrame();
}
setInterval(function(){
draw();
}, 100);
</script>
</body>
</html>
I expect the output to be an animation of a tree growing, but instead I'm getting a blank page.
you should provide more code or a snippet, there are several variables didn't show up in your code
and it's hard to debug your code if u use setInterval, you should make sure your code can work first.
maybe you can try step by step:
draw the whole img on the canvas first. if it works, go next
invoke your draw() function manually, check if the img drawed
invoke more, such assetTimout(draw, 1000), check the result
ok, and i think you can console.log these variables in draw
I'm trying to run a simple truck simulator (sorry for the liking of trucks), but when I try, it seems to not work (also no errors). However, when I run the entire code in the edit section of Bill Mill's Canvas Tutorial, it works. In case if you say it's my browser, this doesn't show "Oops...":
<canvas id="canvas" width="420" height="440" style="border: 1px solid #000;">Oops...
JS:
/*Truck Driving Simulator**/
//set up the canvas
var c = document.getElementById("canvas");
var w = 420;
var h = w+20;
var ctx = c.getContext('2d');
var t = tr(250,250,20,40,'blue');
function tr(iX,iY,iR,iColor){
return{
drawmove: function(){
ctx.beginPath();
ctx.arc(iX, iY, iR, 0, Math.PI*2, true);
ctx.fillStyle = iColor;
ctx.fill();
ctx.closePath();
}
}
}
function p(){
t.drawmove();
}
function init(){
setInterval(function(){
p();
}, 60);
}
init();
JSFiddle: https://jsfiddle.net/yey4xdoq/
Also, even though it shows in the fiddle, it doesn't on my PC.
I:
1. Made sure my browser supports the canvas tag
2. Correctly linked my Js
3. Correctly called the canvas
Hey Im experimenting with some html5 animation and so far I have a square that "falls" whenever I press the button. I was wondering how i could have it go back to the top when it hits the bottom and fall again.
My current code is:
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="200" height="400" style="border:1px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
function draw (x,y){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.save();
var side = 10
var up = 10
ctx.clearRect(0,0,200,400);
ctx.fillStyle = "#FF0000";
ctx.fillRect(x,y,up,side);
ctx.restore();
y += 5;
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
</script>
<button onclick="draw(0,0)">draw</button>
</body>
</html>
Using your variables y, you can simply check if it is below the height of the canvas height.
if( y > c.height ){ // use the canvas height, not the context height
y = 0;
}
Also, the way you're currently calling the timer is a bit inefficient. Instead of :
var loopTimer = setTimeout('draw('+x+','+y+')',30);
I would recommend
var loopTimer = setTimeout(function(){ draw(x,y); },30);
Here's a working example: http://jsfiddle.net/vwcdpLvv/
I've tried everything to solve this problem and nothings working. Posting here is my last resort.
I'm trying to code a simple canvas element and load everything dynamically and nothing is working. I keep getting the error in Google console "Uncaught ReferenceError: ctx is not defined" on game.js:33.
I originally thought it was because common.js is being loaded after the other 2 javascript files so I made a loader file which loads each JS file in the order I want. I did this using $.getScript() and the $.when() function . Unfortunately, this did not work. So the ctx var is being loaded but it's giving me the error for some reason.
I've included the files below. Thanks in advance for any help.
EDIT: I just tried taking all the code out of each individual JS file and putting them in the same one in the order they are meant to be in and it works fine now. But it would be nice to know why it was not working at all. As it's going to get very hectic having all my code in 1 file. Thank you.
index.php
<!doctype>
<html>
<head>
<title>Game - Unknown</title>
<link rel="stylesheet" href="./assets/css/default.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.3.min.js"></script>
<!--<script src="./assets/js/loader.js"></script>-->
<script src="./assets/js/common.js"></script>
<script src="./assets/js/graphics.js"></script>
<script src="./assets/js/game.js"></script>
</head>
<body>
<canvas id="viewport"></canvas>
</body>
</html>
common.js
$(document).ready(function(){
// Setup the canvas game context for 2D
var canvas = document.getElementById("viewport");
var ctx = canvas.getContext("2d");
// Update the canvas dimensions to match window size when changed
$(window).resize(function(){canvasResize()}); canvasResize();
function canvasResize(){
var cWidth = window.innerWidth;
var cHeight = window.innerHeight;
canvas.width = cWidth;
canvas.height = cHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, cWidth, cHeight);
}
// Get center of things - Useful for centering images on canvas
function getCenter(dim){ return dim / 2 }
});
graphics.js
$(document).ready(function(){
function gfxTile(x, y, w, h, r, g, b, a)
{
ctx.fillStyle = "rgb(60, 60, 100)";
ctx.beginPath();
//ctx.moveTo(x + h / 2, y + w / 2);
ctx.moveTo(10, 10);
ctx.lineTo(105, 25);
ctx.lineTo(25, 105);
ctx.lineTo(25, 105);
ctx.closePath();
ctx.fill();
}
});
game.js
$(document).ready(function(){
// START TEMPORARY
var mapSizeX = 10;
var mapSizeY = 10;
var mapArray = new Array();
function createMap()
{
for(x = 0; x < mapSizeX; x++)
{
mapArray[x] = [];
for(y = 0; y < mapSizeY; y++)
{
mapArray[x][y] = 0;
}
}
}
// END TEMPORARY
setInterval(mainLoop, 50);
function mainLoop()
{
//gfxTile(10, 10, 40, 40, 50, 50, 50, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
});
var ctx = canvas.getContext("2d"); created a variable called ctx in the scope of the function you passed into $(document).ready();
When the function inside of game.js executes, there is no ctx variable in its scope, or the parent scope, window.
An easy fix would be changing
var ctx = canvas.getContext("2d");
to
window.ctx = canvas.getContext("2d");
Your ctx variable is already on a reachable namespace, your problem is basically a result of loading files with no order and priority. You can however use a script loader to solve the problem and make sure your variable is already defined before using it.
In this example I'm using the head.js script loader.
<script src="js/head.js"></script>
<script>
head.js(
"http://code.jquery.com/jquery-1.9.1.min.js",
"http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.3.min.js",
"js/common.js",
"js/graphics.js",
"js/game.js"
);
You can optimize your code even more using requireJS to expose only the namespaces you want . Check them out.
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.