When I'm referencing my JavaScript file to my index.html file (two separate files in the same folder), and I load the html file in a browser, the drawing i made in the javascript file doesnt show in the canvas.
Here is this HTML code:
<!DOCTYPE html>
<html>
<head>
<title>snake</title>
<script language="javascript" type="text/javascript" src="snake.js"></script>
</head>
<body>
<canvas id="dots" height="500" width="500"></canvas>
</body>
</html>
and here is the JavaScript:
function snake() {
var canvas = document.getElementById("dots");
var snakehead = canvas.getContext('2d');
snakehead.beginPath();
snakehead.arc(100, 75, 50, 0, 2 * Math.PI);
snakehead.stroke();
snakehead.fillStyle = "#2776ff";
snakehead.fill();
}
snake();
in JS-fiddle the code works, it looks like this: https://jsfiddle.net/j2ny6gaf/72/
I'm also getting some errors from JSLint.
"Missing use of 'strict' statement, on the var canvas = document.getElementById
"Combine this with the previous var statement var snake = canvasgetcontext
and a ERROR;
"Document is not defined.[no-undef]
Try adding your script inside the head section (script src=“file-name.js” /script) and try adding a canvas size.
Try
window.onload = function snake() {...}
Try using the script tag
<script type="text/javascript" src="snake.js"></script>
Inside the head section.
Related
I am trying to make the background of the canvas but I can't use getContext. I get the error:
Uncaught TypeError: Cannot read property 'getContext' of null at game.js:4
Html
<!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8">
<title>Game</title>
</head>
<body>
<script src="game.js"></script>
<canvas id="canvas" width="100" height="320"></canvas>
</body>
</html>
Javascript
const canvas = document.getElementById('canvas');
if (canvas != null) {
ctx = canvas.getContext("2d");
} else {
console.log('wtf happen');
}
function draw(){
ctx.background(255,0,0);
}
I have already tried using the post: Cannot read property 'getContext' of null
but it did not help me.
This is because you are calling your javascript before the element is added to the page/DOM and the browser runs/loads code/HTML synchronously (one line at a time).
So, this leaves us with three options:
Use Defer
Add defer to your script tag this will load it after the dom is ready
<script src="game.js" defer></script>
Move the script tag after the canvas
Moving the tag after the canvas will allow the canvas to be ready when the script runs
<canvas id="canvas" width="100" height="320"></canvas>
<script src="game.js"></script>
Wrap your code within the DOMContentLoaded event
Putting your code within this event will run the code after the DOM has loaded.
document.addEventListener('DOMContentLoaded', e => {
const canvas = document.getElementById('canvas');
if (canvas != null) {
ctx = canvas.getContext("2d");
} else {
console.log('wtf happen');
}
function draw(){
ctx.background(255,0,0);
}
})
What I want do find out is how I can make this work so it makes a red box at location 100,100, using a function as my main function and another function to draw the image but I want it to be in a different js file.
2 js files and 1 html file.
Code
//HTML code
<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset="UTF-8">
<title>Prufa Einar</title>
</head>
<body>
<canvas id = "myCanvas" width="600" height = "600"
style ="border: 1px solid black;">
<script type = "text/javascript" src "draw.js"></script>
<script type = "text/javascript" src "main.js"></script>
<script type = "text/javascript">
main();
</script>
</body>
</html>
//first js.file
var canvas;
var ctx;
var main = function()
{
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
draw(ctx);
};
//second js file
var draw = function(ctx)
{
{
ctx.fillStyle = "Red";
ctx.fillRect(100,100,20,20);
}
};
Looks like you need equal sign after src.
src=""
and canvas out of head into body instead
I can't get this to work on my public webpage. I've made sure all permissions on files are correct, but when I go to the site, it just shows a blank page. It's supposed to have a matrix-like effect. I edited it through Codepen.io, but when I transfer it over to actual files and upload them, nothing works.
HTML:
<html><head>
<script src="(link the js file attached that is in the directory of my webpage)" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<meta charset="utf-8">
<title>Matrix</title>
</head>
<body>
<div align="center">
<canvas id="canvas" width="500" height="500">
</canvas><br/><br/>
</div>
</body>
</html>
JavaScript:
//this is my matrix.js file
$(document).ready(function(){
var s=window.screen;
var width = canvas.width=s.width;
var height = canvas.height;
var inLink = false;
var yPositions = Array(300).join(0).split('');
var context=canvas.getContext('2d');
var draw = function () {
context.fillStyle='rgba(0,0,0,.05)';
context.fillRect(0,0,width,height);
context.fillStyle='#0F0';
canvas.addEventListener("click", on_click, false);
canvas.addEventListener("mousemove", on_mousemove, false);
context.fillText(linkText,10,50);
context.font = '12pt Georgia';
yPositions.map(function(y, index){
text = String.fromCharCode(1e3+Math.random()*33);//determines characters randomly from this specific font
x = (index * 10)+10;
canvas.getContext('2d').fillText(text, x, y);
if(y > 100 + Math.random()*1e4)
{
yPositions[index]=0;
}
else
{
yPositions[index] = y + 10;
}
});
};
RunMatrix();
function RunMatrix()
{
if(typeof Game_Interval != "undefined") clearInterval(Game_Interval);
Game_Interval = setInterval(draw, 33);
}
})
You have to include your javascript files after the libraries they depend upon
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript"></script>
<script src="(link the js file attached that is in the directory of my webpage)" type="text/javascript"></script>
Also, consider using a newer version of jQuery
try adding...
var canvas = document.getElementById('canvas');
at the start of your $(document).ready function...
$(document).ready(function(){
var canvas = document.getElementById('canvas');
....
basically you are referencing 'canvas', which doesn't appear to exist yet..
also make sure you're including jquery before any libraries or scripts that attempt to use it!
Easeljs - Hyperlinking.
Out of an easeljs script: how can I hyperlink to another web site?
For instance: when an onClickEvent occurs another window would open - in my case I want to send a variable, an ID to another page with an SQL request on the ID for more details.
Any sample would be great.
When you click on the red shape it will open google.com. You can add the hyperlink any easeljs object like this.
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<style>
#myCanvas{
background-color:#CCC;
}
</style>
<script src="easeljs-0.7.1.min.js"></script>
<script src="jquery-1.7.2.min.js"></script>
<script>
var canvas, stage;
$().ready(function(e) {
canvas = document.getElementById("myCanvas");
stage = new createjs.Stage(canvas);
var shape = new createjs.Shape();
shape.graphics.beginFill("#ff0000").drawRect(0, 0, 100, 100);
stage.addChild(shape);
shape.x = 200, shape.y = 100;
shape.addEventListener("click", goURL, false);
stage.update();
});
function goURL(){
window.open("http://google.com");
}
</script>
</head>
<body onload="init()">
<canvas id="myCanvas" width="500" height="400">
</canvas>
</body>
</html>
http://www.w3schools.com/jsref/met_win_open.asp
window.open(URL,name,specs,replace);
But be aware that popups/new tabs like this might be blocked by the browser if not followed an user-event. You could also retrieve the details via jQuery.get or jQuery.ajax ect.. and then display the information directly in your application.
You can also use window.location in case you only want to redirect to another page instead of open a new window/tab. For example:
var id = 0 //the variable you want to pass;
shape.addEventListener("click", gotoURL);
function gotoURL(){
location.assign( 'http://yoursite.com/search?id='+id );
}
I am using EaselJS and want to allow for backwards compatibility with ExplorerCanvas.
This should be possible using the following code (see here):
createjs.createCanvas = function () { ... return canvas implementation here ... }
However, If I put an alert in this function and run the code, the function is never run.
How do I go about getting this to work?
Edit:
Here is a simplified example of the code I am using:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='/Scripts/jquery-1.7.1.js'></script>
<script src="/Scripts/excanvas/excanvas.compiled.js"></script>
<script src="/Scripts/easeljs/lib/easeljs-0.5.0.min.js"></script>
<script src='/Scripts/core/jquery.mousewheel.js'></script>
<style>
canvas
{
border: 1px solid #ccc;
}
</style>
<script type='text/javascript'>
$(document).ready(function () {
// Variables
var img;
var stage;
var bmp;
// Bindings
$('#load').click(function () { initialize() }); // DELETE
// Functions
function initialize() {
img = new Image();
img.onload = imageLoadedEvent;
img.src = '/Scripts/viewer/June.jpg';
}
function imageLoadedEvent() {
var canvasElement = generateContext('testCanvas', 400, 400);
stage = new createjs.Stage('testCanvas');
bmp = new createjs.Bitmap(img);
stage.autoClear = true;
stage.addChild(bmp);
stage.update();
}
function generateContext(canvasID, width, height) {
var canvasElement = document.createElement('canvas');
if (typeof (G_vmlCanvasManager) != 'undefined')
canvasElement = G_vmlCanvasManager.initElement(canvasElement);
canvasElement.setAttribute("width", width);
canvasElement.setAttribute("height", height);
canvasElement.setAttribute("id", canvasID);
document.getElementById('viewer').appendChild(canvasElement);
}
});
</script>
</head>
<body>
<div id='viewer'>
<button id='load'>load</button>
</div>
</body>
</html>
This example will run in Chrome and IE9 as a native canvas element is created and used. However in IE8 it fails.
I ran across this issue as well, trying to get ExCanvas to play nice with EaselJS. Here is how I got it working. Hope this helps with your image issue.
Get the source code for EaselJS : https://github.com/gskinner/EaselJS.git. This will get all the javascript files separated out into their own parts.
Copy all those files over to a "easel" folder in your project directory.
The order in which the files are loaded is important, so see below on how to do it.
EaselJS has an option to override the createCanvas method, which is required to use ExCanvas with it. This happens after loading the SpriteSheet.js file, and BEFORE loading Graphics.js, DisplayObject.js, Container.js, etc. In the code below, I used jQuery to load the rest of the js files that easelJs needed. This all happens in the $(document).ready() function.
If done correctly, you should see a 700 x 700 canvas with a red line from top left to bottom right in IE (tested in 8).
head>
<!--
Load ExCanvas first, and jquery
-->
<script type='text/javascript' src='./javascript/excanvas.js'></script>
<script type='text/javascript' src='./javascript/jquery-1.8.2.min.js'></script>
<!--
Have to load Easel js files in a certain order, and override the createCanvas
function in order for it to work in < IE9.
-->
<script type='text/javascript' src='./javascript/easel/UID.js'></script>
<script type='text/javascript' src='./javascript/easel/Ticker.js'></script>
<script type='text/javascript' src='./javascript/easel/EventDispatcher.js'></script>
<script type='text/javascript' src='./javascript/easel/MouseEvent.js'></script>
<script type='text/javascript' src='./javascript/easel/Matrix2D.js'></script>
<script type='text/javascript' src='./javascript/easel/Point.js'></script>
<script type='text/javascript' src='./javascript/easel/Rectangle.js'></script>
<script type='text/javascript' src='./javascript/easel/Shadow.js'></script>
<script type='text/javascript' src='./javascript/easel/SpriteSheet.js'></script>
<script type='text/javascript'>
var canvas, stage;
createjs.createCanvas = function () { return getCanvas(); };
function getCanvas() {
// This is needed, otherwise it will keep adding canvases, but it only use the last one it creates.
canvas = document.getElementById("myCanvas");
if (canvas != null) {
document.getElementById("container").removeChild(canvas);
}
canvas = document.createElement("canvas");
document.getElementById("container").appendChild(canvas);
if (typeof (G_vmlCanvasManager) != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
canvas.setAttribute("height", "700");
canvas.setAttribute("width", "700");
canvas.setAttribute("style", "height:700px; width:700px;");
canvas.setAttribute("id", "myCanvas");
}
return canvas;
}
</script>
<script type="text/javascript">
$(document).ready(function () {
loadOtherScripts();
stage = new createjs.Stage(canvas);
// Draw a red line from top left to bottom right
var line = new createjs.Shape();
line.graphics.clear();
line.graphics.setStrokeStyle(2);
line.graphics.beginStroke("#FF0000");
line.graphics.moveTo(0, 0);
line.graphics.lineTo(700, 700);
stage.addChild(line);
stage.update();
});
function loadOtherScripts() {
var jsAr = new Array(13);
jsAr[0] = './javascript/easel/Graphics.js';
jsAr[1] = './javascript/easel/DisplayObject.js';
jsAr[2] = './javascript/easel/Container.js';
jsAr[3] = './javascript/easel/Stage.js';
jsAr[4] = './javascript/easel/Bitmap.js';
jsAr[5] = './javascript/easel/BitmapAnimation.js';
jsAr[6] = './javascript/easel/Shape.js';
jsAr[7] = './javascript/easel/Text.js';
jsAr[8] = './javascript/easel/SpriteSheetUtils.js';
jsAr[9] = './javascript/easel/SpriteSheetBuilder.js';
jsAr[10] = './javascript/easel/DOMElement.js';
jsAr[11] = './javascript/easel/Filter.js';
jsAr[12] = './javascript/easel/Touch.js';
for (var i = 0; i < jsAr.length; i++) {
var js = jsAr[i];
$.ajax({
async: false,
type: "GET",
url: js,
data: null,
dataType: 'script'
});
}
}
</head>
<body>
<div id="container"></div>
</body>
</html>
You should instantiate the quasi canvas element by making reference to the original canvas source as provided on the project page example:
<head>
<!--[if lt IE 9]><script src="excanvas.js"></script><![endif]-->
</head>
var el = document.createElement('canvas');
G_vmlCanvasManager.initElement(el);
var ctx = el.getContext('2d');
EDIT:
After further investigation i came to the following conclusions!
There are multiple reasons for not being able to include the image into the canvas:
1st probably there is a bug in the excanvas code for not being able to mimic the native canvas features. I used with more success the modified sancha code, which you can obtain here: http://dev.sencha.com/playpen/tm/excanvas-patch/excanvas-modified.js. See live example here: http://jsfiddle.net/aDHKm/ (try it on IE).
2nd before Easeljs initialize the core objects and classes first is searching for the canvas element existence. Because IE < 9 doesn't have implemented the canvas it's obvious that easeljs core graphics API's can not be instantiated. I think these are the two main reasons that your code is not working.
My suggestion is to try to remake the code without the easeljs. I made a fiddle with the necessary modification to show you how can be done without easeljs: http://jsfiddle.net/xdXrw/. I don't know if it's absolute imperative for you to use easeljs, but certainly it has some limitations in terms of IE8 hacked canvas.