How to make an Hello World Web Page using the CANVAS object.
Open your Hello World web page in your text editor and save it as something new like 'HelloWorldv2.html' or whatever!
|
The Header
Life now gets a bit more complicated but don't panic! You are going to add a JavaScript script to your header. This will tell the machine how to draw a blue rectangle and write 'Hello World' in the middle of it.
<!DOCTYPE HTML>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<script type="text/javascript">
function draw() {
var canvas = document.getElementById("MyCanvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle ="white";
ctx.fillText("Hello World",200, 100);
}
}
</script>
</head>
So open your text editor, copy the stuff above in and save it as something like "MyHelloWorld1.html" etc.
The program won't work just yet as it has a head but no body!
The script tag tells the machine that some JavaScript is on the way.
function draw() { is the opening of the definition of a short computer program or function. I have called it 'draw()' because this will be our main drawing program in the more complicated examples that follow.
Don't worry about the details of the following lines. These are what you do to get the program to work.
var canvas.. and ..if etc line. This tells the machine to get the Canvas area of the computer screen for your webpage.
var ctx line. This tells the machine to get the actual bit it draws and writes on.
ctx.fillstyle etc. This means - make it blue!
ctx.fillRect etc. Make a big blue rectangle
ctx.fillstyle etc Now make the colour white
ctx. fillText etc. Make the colour white.
Then there are two } } brackets. These complete the statements begun higher up the page. If these aren' included then the program won't work.
Finally you tell the machine that it has reached the end of the script.
|
The Body
Add this code to the header and then save it.
<body >
<p>Hello World</p>
<canvas id="MyCanvas" width="500" height="500" > </canvas>
</body>
</html>
This is exactly the same as in the first example except for the canvas tag. This creates a canvas object and gives it a name and size.
|
Running The Code
You can just double click on your file in its folder. Or drag and drop the file into an open window of your browser.
If the code doesn't work check that compatibility (tools menu in IE10+) is turned off. Canvas objects are part of HTML5 so your browser won't run it if it thinks that the page needs rendering as an earlier version of HTML.
Example 2.
You can make the font bigger by inserting this piece of code above the 'Hello World' writing line.
ctx.font = "italic 36px/2 Unknown Font, sans-serif";
This means use the italic version of the font and make it bigger!!
|
last updated 3rd September 2014