Canvas: Difference between revisions

From XPUB & Lens-Based wiki
No edit summary
No edit summary
Line 1: Line 1:
The [[wikipedia:Canvas element|canvas]] tag was introduced by Apple and has been [http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html standardized to become part of HTML5].
The [[wikipedia:Canvas element|canvas]] tag was introduced by Apple and has been [http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html standardized to become part of HTML5].


To use it, you add the canvas tag to your HTML page, then use javascript draw on it.


Get the canvas tag:
<canvas id="canvas" showsrc>
 
function draw() {
c=document.getElementById("c")
   c = document.getElementById("canvas");
 
   p = c.getContext("2d");
Get the "context" (like a paper):
   p.fillRect(50, 50, 150, 150);
 
p=c.getContext("2d");
 
Draw something!
 
p.fillRect(0, 0, 100, 100);
 
== Examples ==
 
Here is a complete HTML page with a working canvas:
 
<source lang="javascript"><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script>
function draw(){
  c = document.getElementById("canvas")
  //console.log("c is",c)
  p = c.getContext("2d")
  x = 10
  while (x<300) {
    p.strokeRect(x,100,20,40)
    x+=60
  }
}
</script>
</head>
<body onload="draw()">
<h1>Hello canvas</h1>
<canvas id="canvas" width="640" height="640" style="border: 3px dotted red"></canvas>
</body>
</html>
</source>
 
Here's the output:
 
<canvas id="c1">  
function draw(){
   c = document.getElementById("c1")
  //console.log("c is",c)
   p = c.getContext("2d")
   x = 10
  while (x<250) {
    p.strokeRect(x,100,20,40)
    x+=60
  }
}
}
</canvas>
</canvas>


Variation: When the loop reaches the end of page it breaks the line.
== Loop ==
It redefines the "x" value to the begin of the line and adds 40px to "y".


<canvas id="c2" width="300" height="300" showsrc="true">
== Template ==
function draw() {
    c = document.getElementById("c2");
    p = c.getContext("2d");
    hands = 1;
    x = 20;
    y = 20;
    while (hands < 100) {
        //console.log(hands);
        p.strokeRect(x,y,20,20);
        x = x + 50;
        hands++;
        if (x > 600) {
            x = 20;
            y = y + 40;
        }
    }
}
</canvas>


x
== Links ==
== Links ==



Revision as of 15:54, 25 September 2012

The canvas tag was introduced by Apple and has been standardized to become part of HTML5.

To use it, you add the canvas tag to your HTML page, then use javascript draw on it.

<canvas id="canvas" showsrc> function draw() {

 c = document.getElementById("canvas");
 p = c.getContext("2d");
 p.fillRect(50, 50, 150, 150);

} </canvas>

Loop

Template

x

Links