HTML 5 Canvas
HTML 5 Canvas
The canvas element is used to draw graphics on web pages.
What is Canvas?
HTML5’s canvas element uses JavaScript to draw images on a web page.
The canvas is a rectangular area that you can control every pixel of.
canvas has many ways to draw paths, rectangles, circles, characters, and add images.
Create Canvas Element
Add canvas element to HTML5 page.
Specify the id, width and height of the element:
Draw through JavaScript
The canvas element itself has no drawing capabilities. All drawing work must be done inside JavaScript:
JavaScript uses id to find the canvas element:
var c=document.getElementById("myCanvas");
Then, create the context object:
var cxt=c.getContext("2d");
getContext("2d") object is a built-in HTML5 object that has Multiple ways to draw paths, rectangles, circles, characters, and add images.
The following two lines of code draw a red rectangle:
cxt.fillStyle="#FF0000";
cxt.fillRect(0,0,150,75);
The fillStyle method dyes it red, and the fillRect method specifies the shape, position and size.
Understanding coordinates
The fillRect method above has parameters (0,0,150,75).
Means: Draw a 150x75 rectangle on the canvas, starting from the upper left corner (0,0).
As shown in the figure below, the X and Y coordinates of the canvas are used to position the painting on the canvas.
把鼠标悬停在下面的矩形上可以看到坐标:
Example - Circle
Draw a circle by specifying the size, color and position:
canvas element:
Example - Gradient
Draw a gradient background using the color you specify:
Example - Image
Place an image to On canvas: