Canvas works in HTML file, but not javascript file - javascript

I just finished my first JavaScript book, "Head First HTML5", and I'm feeling quite dumb. If i put the script in the HTML file it works, but doesn't work in a separate JavaScript file.
HTML file:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<script src="canArt.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="800"></canvas>
</body>
</head>
JS file:
window.onload = init();
function init() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (30, 30, 55, 50);
}
please help.

Your immediately executing the init function by including the parens and assigning the result of init, which is nothing, to the onload handler...
change:
window.onload = init();
to:
window.onload = init;
http://jsfiddle.net/sFmNw/

Related

canvas.getContext("2d"); not working

I am getting the following Error
Error: Uncaught TypeError: Cannot read property 'innerHTML' of null
at script.js:1
I have tried everything I could think of but nothing works.
var canvas = document.getElementById("can").innerHTML;
var ctx = canvas.getContext("2d");
ctx.fillStyle = ("green");
ctx.fillRect(0, 0, 300, 200);
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<script src="script.js"></script>
<!-- Canvas -->
<canvas id="can" width="300" height="200" style="border:4px solid red;">
</canvas
</body>
</html>
Okay there are two serious errors.
You're trying to get the element before the DOM is fully loaded. Therefore the canvas note is not reachable. See addEventListener
and DOMContentLoaded.
Remove .innerHTML. getContext appends on the node not on the content.
document.addEventListener('DOMContentLoaded', function() {
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 300, 200);
});
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<script src="script.js"></script>
<!-- Canvas -->
<canvas id="can" width="300" height="200" style="border:4px solid red;">
</canvas>
</body>
</html>
1. Script error when using canvas
Use var canvas = document.getElementById("can");
Not var canvas = document.getElementById("can").innerHTML();
See W3C - Canvas
2. Add an event listener when the document is ready, then execute your script
See W3C - DOM Event Listener example
function doSomething() {
var canvas = document.getElementById("can");
var ctx = canvas.getContext('2d');
/*
another scripts...
*/
}
window.addEventListener('onload', doSomething, false);
There are two things.
First, you don't need .innerHTML as other answers stated.
Second, you either have to run you script at the window load event like so:
window.addEventListener('load', function () {
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
ctx.fillStyle = ("green");
ctx.fillRect(0, 0, 300, 200);
});
Or you should load the javascript after the canvas tag.

How to draw rectangles in jsf project?

My project is JSF+PRIMEFACES+JPA and i want to draw rectangles in a jsf web page (XHTML) .
that draw need to be showen after i click on a button based on a list of rectangle that already existe in the managed bean .
its possible to do that just with JSF and primefaces ? or i need to introduce javascript or something else ?
Update 1 :
i fount that richfaces have paint2d option . It'is possible to use just this functionnality from richfaces in my project ?
I think that you want this:
<!doctype html>
<html>
<head>
<title>Example</title>
<meta charset='utf-8' />
</head>
<body>
<input type="button" value="Click Me" onclick="changeColor()" />
<canvas id='example'>Somewhat</canvas>
<script>
var changeColor = function(){
var colors = ['red' ,'green','blue','yellow','brown','azure','gold'];
var example = document.getElementById("example"),
context = example.getContext('2d');
example.height = 480;
example.width = 640;
context.beginPath();
context.rect(188, 50, 200, 100);
context.fillStyle = colors[parseInt(Math.random()*colors.length)];
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
}
</script>
</body>
</html>
Since the 5.1.8 elite release (or the 5.2-SNAPSHOT), Primefaces has the diagram component. It can create images you have above, so maybe that is something you cab use
I know that in js one must use canvas. Here simpliest example:
You can write javascript handler to capture click event and then invoke code that image a rectangle
<!doctype html>
<html>
<head>
<title>pathExample</title>
<meta charset='utf-8' />
</head>
<body>
<canvas id='example'>Обновите браузер</canvas>
<script>
var example = document.getElementById("example"),
context = example.getContext('2d');
example.height = 480;
example.width = 640;
context.beginPath();
context.rect(188, 50, 200, 100);
context.fillStyle = 'red';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
</script>
</body>
</html>

Javascript Onclick Functions

Writing a simple script to have two buttons. One button animates a "painting" feature where rectangles follow the cursor around the canvas. The other button would display a rectangle that follows the canvas but doesn't leave a trail like the other. I have the buttons linked to do different functions. Right now the follow button doesn't work, it does clear the canvas but it still allows you to paint. It seems that the paint function is still running after I hit the follow button. Any help is appreciated.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
</head>
<body>
<input type="button" value="Paint" onclick="isPaint()">
<input type="button" value="Follow" onclick="isFollow()">
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
function isPaint(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//change draw color
ctx.fillStyle = "#FF0000";
ctx.clearRect(0,0,500,500);
canvas.addEventListener("mousemove", function(event) {
ctx.fillRect(event.x,event.y,10,10);
})
}
function isFollow(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//change draw color
ctx.fillStyle = "#FF0000";
ctx.clearRect(0,0,500,500);
}
</script>
</body>
</html>
Work for me : http://jsfiddle.net/XF7m4/1/
Using document.getElementById("paint").onclick= function (){
PS :And think to remove the mousemouse listener ;)
To achieve what you are trying to do you will need to enhance your code a little more.
The main idea is to bind the mousemove event only once and clear the canvas if it is to behave like a follow.
Try using the following code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas</title>
</head>
<body>
<input type="button" value="Paint" onclick="CanvasPainter.paint()" />
<input type="button" value="Follow" onclick="CanvasPainter.follow()" />
<canvas id="myCanvas" width="500" height="500"></canvas>
<script type="text/javascript">
(function () {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//change draw color
ctx.fillStyle = "#FF0000";
var CanvasPainter = {
isPaint: false,
isFollow: false,
paint: function () {
this.isPaint = true;
this.isFollow = false;
return;
},
follow: function () {
this.isPaint = false;
this.isFollow = true;
return;
}
};
window.CanvasPainter = CanvasPainter;
canvas.addEventListener("mousemove", function (event) {
if (CanvasPainter.isPaint || CanvasPainter.isFollow) {
if (CanvasPainter.isFollow) {
// Clear canvas on every mousemove if it is a follow
ctx.clearRect(0, 0, 500, 500);
}
ctx.fillRect(event.x, event.y, 10, 10);
}
return;
});
return;
})();
</script>
</body>
</html>
Hope this helps!
Your isPaint() function is adding an event listener for "mousemove" to the canvas, but it isn't getting removed in the isFollow() function. If you remove your listener in the isFollow() function this should fix your problem.

Why does a specific method have to be located at a specific location inside of JavaScript and cannot be moved around?

My question is why does drawScreen have to be located where it is and cannot be moved outside of the method. It is like a method inside a method. I think that this is where I am still weak on JavaScript because there seems times when method, like this one, should be able to be moved outside of where it is as long as it can be called from some point inside of the script.
Question: Why does the drawScreen() method have to be located where it is in the code?
Code Here:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chapter 1 Example 6 Canvas Sub Dom Example </title>
<script src="modernizr.js"></script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);
var Debugger = function () { };
Debugger.log = function (message) {
try {
console.log(message);
} catch (exception) {
return;
}
}
function eventWindowLoaded () {
canvasApp();
}
function canvasSupport () {
return Modernizr.canvas;
}
function canvasApp () {
if (!canvasSupport()) {
return;
}
var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
Debugger.log("Drawing Canvas");
**function drawScreen() {
//background
context.fillStyle = "#ffffaa";
context.fillRect(0, 0, 500, 300);
//text
context.fillStyle = "#000000";
context.font = "20px Sans-Serif";
context.textBaseline = "top";
context.fillText ("Hello World!", 195, 80 );
//image
var helloWorldImage = new Image();
helloWorldImage.onload = function () {
context.drawImage(helloWorldImage, 155, 110);
}
helloWorldImage.src = "helloworld.gif";
//box
context.strokeStyle = "#000000";
context.strokeRect(5, 5, 490, 290);
}**
drawScreen();
}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="300">
<div>A yellow background with an image and text on top
<ol>
<li>The text says "Hello World"</li>
<li>The image is of the planet earth.</li>
</ol>
</div>
</canvas>
</div>
</body>
</html>
JavaScript has lexical scope, so it inherits the scope of outer functions (scope is dependant on where functions are located in source code).
In order to move it out, you'd need to either pass it the data it needs (context) or make it available via some other means.

drawImage() not working - Firebug shows: NS_ERROR_XPC_BAD_CONVERT_JS

Why is this little script not working?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<canvas id="can" height="500" width="500"></canvas>
<script type="text/javascript">
var image = new Image().src="1.jpg";
context = document.getElementById("can").getContext("2d");
context.drawImage(image,10,10,480,480);
</script>
</body>
</html>
Firebug in Firefox (latest Version) shows:
NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument arg 0 [nsIDOMCanvasRenderingContext2D.drawImage]
[Bei diesem Fehler anhalten]
context.drawImage(image,10,10,480,480);
Chrome can't show the image either, they just say ERROR.
image.src is async, you need to draw it with a callback.
var image = new Image;
image.onload = function() { context.drawImage(image, 10, 10, 400, 400); }
image.src = .....
All you need to do is change:
ctx.drawImage(i, 0, 0, arg.width, arg.height);
to:
ctx.drawImage(arg.img, 0, 0, arg.width, arg.height);

Categories

Resources