5月28日 02:57
How to get the 2D context of Canvas? Please list some basic Canvas drawing methods.
Getting the 2D context of Canvas
To get the 2D context of Canvas, you first need to get a reference to the Canvas element, then call its getContext() method with the parameter "2d". Example code is as follows:
javascript// Get Canvas element const canvas = document.getElementById('myCanvas'); // Ensure browser supports Canvas if (canvas.getContext) { // Get 2D context const ctx = canvas.getContext('2d'); // Now you can use ctx for drawing operations } else { // Browser does not support Canvas console.log('Your browser does not support the Canvas element.'); }
Basic Canvas drawing methods
The Canvas 2D context provides rich drawing methods, here are some of the most basic ones:
-
Drawing rectangles:
fillRect(x, y, width, height): Draw filled rectanglestrokeRect(x, y, width, height): Draw rectangle borderclearRect(x, y, width, height): Clear specified rectangular area
-
Drawing paths:
beginPath(): Start new pathmoveTo(x, y): Move to path start pointlineTo(x, y): Draw line to specified pointarc(x, y, radius, startAngle, endAngle, anticlockwise): Draw arcclosePath(): Close pathfill(): Fill pathstroke(): Stroke path
-
Setting styles:
fillStyle: Set fill style (color, gradient or pattern)strokeStyle: Set stroke stylelineWidth: Set line widthlineCap: Set line end stylelineJoin: Set line join style
-
Drawing text:
fillText(text, x, y, maxWidth): Draw filled textstrokeText(text, x, y, maxWidth): Draw text borderfont: Set font styletextAlign: Set text alignmenttextBaseline: Set text baseline
-
Drawing images:
drawImage(image, dx, dy): Draw imagedrawImage(image, dx, dy, dWidth, dHeight): Scale and draw imagedrawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight): Crop, scale and draw image
Example: Drawing a simple graphic
javascriptconst canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // Draw a red filled rectangle ctx.fillStyle = 'red'; ctx.fillRect(10, 10, 100, 100); // Draw a blue bordered circle ctx.beginPath(); ctx.arc(150, 60, 50, 0, Math.PI * 2); ctx.strokeStyle = 'blue'; ctx.lineWidth = 2; ctx.stroke();
Through the combination of these basic methods, developers can create various complex graphics and effects.