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:

  1. Drawing rectangles:

    • fillRect(x, y, width, height): Draw filled rectangle
    • strokeRect(x, y, width, height): Draw rectangle border
    • clearRect(x, y, width, height): Clear specified rectangular area
  2. Drawing paths:

    • beginPath(): Start new path
    • moveTo(x, y): Move to path start point
    • lineTo(x, y): Draw line to specified point
    • arc(x, y, radius, startAngle, endAngle, anticlockwise): Draw arc
    • closePath(): Close path
    • fill(): Fill path
    • stroke(): Stroke path
  3. Setting styles:

    • fillStyle: Set fill style (color, gradient or pattern)
    • strokeStyle: Set stroke style
    • lineWidth: Set line width
    • lineCap: Set line end style
    • lineJoin: Set line join style
  4. Drawing text:

    • fillText(text, x, y, maxWidth): Draw filled text
    • strokeText(text, x, y, maxWidth): Draw text border
    • font: Set font style
    • textAlign: Set text alignment
    • textBaseline: Set text baseline
  5. Drawing images:

    • drawImage(image, dx, dy): Draw image
    • drawImage(image, dx, dy, dWidth, dHeight): Scale and draw image
    • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight): Crop, scale and draw image

Example: Drawing a simple graphic

javascript
const 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.

标签:Canvas