In that function
- Make a Javascript variable holding the canvas. In this example it's called 'paper'.
- Get a second javascript variable that holds a pen you can draw with. It's sometimes called a "context" but I named it "pen".
- To make a colored in rectangle, use fillRect(x,y,width,height).
pen.fillStyle = "red";
pen.fillRect(1,2,300,400);
- To make an outline of a rectangle, use strokeRect(x,y,width,height).
pen.strokeStyle = "red";
pen.strokeRect(1,2,300,400);
- To draw lines,
- use beginPath()
- Play connect the dots with moveTo(x,y) and lineTo(x,y)
- use stroke()
- use closePath()
// Draw a line in orange from (10,10) to (50,30)
pen.beginPath();
pen.strokeStyle = "orange";
pen.moveTo(10,10);
pen.lineTo(50,30);
pen.stroke();
pen.closePath();
- To a polygon
- use beginPath()
- Play connect the dots with moveTo(x,y) and lineTo(x,y)
- use fill()
- use closePath()
// Fill in a triangle with corners (300,200), (300,400), and (400,300)
pen.beginPath();
pen.fillStyle = "pink";
pen.moveTo(300,200);
pen.lineTo(300,400);
pen.lineTo(400,300);
pen.fill();
pen.closePath();
- To draw a circle
- use beginPath()
- use arc(centerX, centerY, radius,0, 2*3.1415, false)
- use stroke() for a hollow circle, or fill() for a colored in circle.
- use closePath()
// A filled in yellow circle with center (50,300) and radius 30
pen.beginPath();
pen.fillStyle = "yellow";
pen.arc(50,300,30,0, 2*3.1415, false);
pen.fill();
pen.closePath();
Here is how to make a canvas.
<canvas id=canvas width=500 height=500 style="border: 10px solid green"></canvas>
Here is the code that draws the stuff above
<script>
window.onload = function draw()
{
var canvas = document.getElementById("canvas");
var pen = canvas.getContext("2d");
// Draw a red filled in rectange from starting at (1,2) that is 300 wide and 400 tall
pen.fillStyle = "red";
pen.fillRect(1,2,300,400);
// Draw a blue outline of a rectange from starting at (1,2) that is 300 wide and 400 tall
// It has a line width of 5.
pen.strokeStyle = "blue";
pen.lineWidth = 5;
pen.strokeRect(1,2,300,400);
// Draw a line in orange from (10,10) to (50,30)
pen.beginPath();
pen.strokeStyle = "orange";
pen.moveTo(10,10);
pen.lineTo(50,30);
pen.stroke();
pen.closePath();
// Draw a line from (100,100) to (200,100) and then a second line from
// (300,200) to (70,30)
pen.beginPath();
pen.strokeStyle = "purple";
pen.moveTo(100,100);
pen.lineTo(200,100);
pen.moveTo(300,200);
pen.lineTo(70,30);
pen.stroke();
pen.closePath();
// Fill in a triangle with corners (300,200), (300,400), and (400,300)
pen.beginPath();
pen.fillStyle = "pink";
pen.moveTo(300,200);
pen.lineTo(300,400);
pen.lineTo(400,300);
pen.fill();
pen.closePath();
// A filled in yellow circle with center (50,300) and radius 30
pen.beginPath();
pen.fillStyle = "yellow";
pen.arc(50,300,30,0, 2*3.1415, false);
pen.fill();
pen.closePath();
}
</script>