HTML Canvas API Flashcards
What Is Canvas API
The Canvas API provides a means for drawing graphics via JavaScript and the HTML element. Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.
What is context?
CanvasRenderingContext2D is the interface that will give access to methods that we can use to draw on canvas. We initiate it by const ctx = canvas.getContext('2d')
What method will draw a rectangle that will be filled with a specific color?
ctx. fillStyle = ‘orange’;
ctx. fillRect(x,y,width, height);
also can be done by
ctx. rect(x,y,width, height);
ctx. fillStyle(‘orange’);
ctx. fill();
What method will draw a rectangle with just borders?
ctx. lineWidth = 5;
ctx. strokeTyle = ‘green’;
ctx. strokeRect(0,0,100,100);
What does clearRect method do?
Clear rect will clear out part of a rectangle. (Often used in animations when you need to clear the whole canvas with each paint).
ctx.clearRect(25,25,140,90)
How do you generate text on the canvas?
- fillText() method:
ctx. font = ‘30px Arial’;
ctx. fillStyle = ‘purple’;
ctx. fillText(‘Hello World’, 400, 50);
- strokeText() method:
ctx. lineWidth = 1;
ctx. strokeStyle = ‘orange’;
ctx. strokeText(‘Hello World’, 400, 100);
What are the path methods and what do they do?
ctx. beginPath() - The beginPath() method is called before beginning each line, so that they may be drawn with different colors.
ctx. moveTo(x,y) - begins a new sub-path at the point specified by the given (x, y) coordinates.
ctx. lineTo(x,y) - adds a straight line to the current subpath by connecting the sub-path’s last point to the specified coordinates.
ctx.closePath() attempts to add a straight line from the current point to the start of the current sub-path.
How do you draw circles on canvas?
ctx.arc(x, y, radius, startAngle, endAngle [, anticlockwise])
to draw a full circle for end angle, you can pcik Math.PI * 2,
to draw half of a circle Math.PI;
What are bezier and quadratic curves?
Bezier and quadratic curves are curves that use control points to control the angle of the curve.
quadraticCurveTo(cp1x, cp1y, x, y)
quadratic curve has just one control point
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
while bezier curve has two control points.