Anyway, as a beginner i think i should start with the very basics (learn to draw).
Let's draw a RECTANGLE
First we will put an id to our Canvas element as we will need it later in our script, then we apply the width and the height of the element. Once we've done all this we have our "drawing field" ready.
Oh, and please let's not forget about the users with older browsers which don't support the Canvas element! All we have to do is to put a text with a warning.
<canvas height="100" id="myCanvas" width="200"> Your browser does not support the canvas element.</canvas>
Now we will start drawing using the script. First we want to make sure that we are drawing our rectange in a right place, that's where we will use the id that we applied to our Canvas element:
var c=document.getElementById("myCanvas");
As for now the browser supports are only for 2D drawings, so here's what we have do:
var cxt=c.getContext("2d");
Now we can start to actually draw our rectangle. First we need to choose the fill color:
cxt.fillStyle="#679900";
Ok, so now we have the color, but we don't have a shape... As you can see for a rectangle it is quite easy to remember, all you have to do is to put "fillRect" and the script will know to draw a rectangle for you. But it also wants to know how big the rectangle you want and where do you want to place it. That's where you should describe the x and y to position your rectangle and then a width and height properties, all separated by comma:
cxt.fillRect(0,0,150,75);
Now let's look at the code all together:
<canvas height="100" id="myCanvas" width="200">
Your browser does not support the canvas element.</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
cxt.fillStyle="#679900";
cxt.fillRect(0,0,150,75);
</script>
Look at the result:
Beautiful! :))
No comments:
Post a Comment