HTML5 HTML5 Canvas and Graphics 1 — Questions and Answers
Question 1: Which method is used to get a 2D drawing context from an HTML5 canvas element?
- getContext('2d') (Correct answer)
- getContext('canvas')
- getDrawingContext()
- context2D()
Correct answer: getContext('2d')
The getContext('2d') method returns a CanvasRenderingContext2D object used for drawing shapes, text, and images on the canvas.
Question 2: What does the canvas fillRect() method do?
- Draws a filled rectangle at the specified position (Correct answer)
- Draws only the outline of a rectangle
- Clears a rectangular area
- Defines a clipping rectangle
Correct answer: Draws a filled rectangle at the specified position
The fillRect(x, y, width, height) method draws a filled solid rectangle using the current fillStyle.
Question 3: Which canvas method is used to draw an arc or circle?
- arc() (Correct answer)
- circle()
- drawCircle()
- ellipse()
Correct answer: arc()
The arc(x, y, radius, startAngle, endAngle, anticlockwise) method adds an arc to the current path, used to draw circles and circular shapes.
Question 4: What is the purpose of beginPath() in HTML5 Canvas?
- Starts a new drawing path, clearing any previous path (Correct answer)
- Begins a canvas fill operation
- Initializes the canvas context
- Opens a new canvas layer
Correct answer: Starts a new drawing path, clearing any previous path
The beginPath() method resets the current path so that subsequent path commands start fresh without connecting to old path segments.
Question 5: Which canvas property sets the color or style used to fill shapes?
- fillStyle (Correct answer)
- fillColor
- shapeColor
- paintStyle
Correct answer: fillStyle
The fillStyle property sets the color, gradient, or pattern used to fill shapes drawn on the canvas.
Question 6: What does the canvas clearRect() method do?
- Clears the specified rectangular area, making it transparent (Correct answer)
- Resets all canvas styles
- Removes the canvas element from the DOM
- Erases the last drawn shape only
Correct answer: Clears the specified rectangular area, making it transparent
The clearRect(x, y, width, height) method erases the pixels in the specified rectangle, making that area transparent.