| Canvas |
<canvas id="myCanvas" width="300" height="200">
Your browser doesn't support the canvas element; please update!
</canvas>
<script>
var myCanvas = document.getElementById("myCanvas");
var myContext = myCanvas.getContext("2d");
// now draw using myContext as shown below
</script>
|
|---|---|
| Draw a line or polygon |
myContext.beginPath(); myContext.moveTo(x1, y1); // y is measured down from top myContext.lineTo(x2, y2); // coordinates need not be integers myContext.lineTo(x3, y3); // add as many segments as desired myContext.strokeStyle = "blue"; myContext.lineWidth = 2; myContext.stroke(); myContext.fillStyle = "yellow"; myContext.fill(); // fill the polygon |
| Draw a rectangle |
myContext.fillStyle = "green"; myContext.fillRect(x, y, width, height); |
| Draw a circle |
myContext.beginPath(); myContext.arc(x, y, r, 0, 2*Math.PI); // use other angles for arcs myContext.fill(); // or myContext.stroke() for open circle |
| Write text |
myContext.font = "30px sans-serif";
myContext.fillStyle = "#8000ff";
myContext.fillText("Hello, Canvas!", x, y); // baseline left x & y
|
| Specify colors |
BlueViolet color name (full list at en.wikipedia.org/wiki/Web_colors)#8000ff hexadecimal rrggbbrgb(128,0,255) values 0 to 255rgba(128,0,255,0.4) with transparency (1.0 is opaque)hsl(270,100%,50%) hue in degrees, saturation%, lightness%hsla(270,100%,50%,0.4) with transparency (1.0 is opaque)
|
| Draw an image |
myImage = new Image(); myImage.src = "imageFile.png"; // .jpg and .gif work too myImage.onload = myFunction; // function to call when ready myContext.drawImage(theImage, x, y); // upper-left corner x & y |
| Clear the canvas |
myContext.clearRect(0, 0, myCanvas.width, myCanvas.height); |
| Coordinate transformations |
myContext.translate(dx, dy); myContext.scale(xScale, yScale); myContext.rotate(angleInRadians); myContext.setTransform(1, 0, 0, 1, 0, 0); // reset |
| Pixel-by-pixel image creation |
image = myContext.createImageData(myCanvas.width, myCanvas.height);
for (y=0; y<myCanvas.height; y++) {
for (x=0; x<myCanvas.width; x++) {
index = (x + y*myCanvas.width) * 4; // index into data array
image.data[index] = redLevel; // 0 to 255
image.data[index+1] = greenLevel;
image.data[index+2] = blueLevel;
image.data[index+3] = transparency; // 255 is opaque
}
}
myContext.putImageData(image, 0, 0); // blast image to screen
|