Start · Sprachen · JavaScript · Referenz · CanvasRenderingContext2D.createConicGradient()

CanvasRenderingContext2D.createConicGradient()

Methode

Erzeugt ein <code>CanvasGradient</code>-Objekt für einen konischen Farbverlauf (Winkelverlauf), der sich um den Punkt <code>(x, y)</code> dreht.

seit JavaScript Baseline 2023: Chrome 99, Edge 99, Firefox 112, Sa Kategorie: webapi

Signatur

CanvasRenderingContext2D.prototype.createConicGradient(startAngle, x, y)

Beschreibung

Die Methode createConicGradient() erzeugt einen konischen Farbverlauf. Die Farben ändern sich dabei nicht mit dem Abstand zum Mittelpunkt wie bei createRadialGradient() und nicht entlang einer Linie wie bei createLinearGradient(), sondern mit dem Winkel um einen Mittelpunkt. Damit lassen sich z. B. Farbkreise, Tortendiagramme mit weichen Übergängen, Tachoanzeigen, Ladekreise oder Metallic-Effekte umsetzen.

Der Verlauf beginnt beim Winkel startAngle (im Bogenmaß) und läuft im Uhrzeigersinn einmal ganz herum. Ein Winkel von 0 zeigt nach rechts (3-Uhr-Position), -Math.PI / 2 nach oben (12 Uhr). Die Farbstopps setzt du wie gewohnt mit CanvasGradient.addColorStop(offset, color), wobei 0 dem Startwinkel und 1 einer vollen Umdrehung entspricht.

Die Methode zeichnet selbst nichts. Das zurückgegebene Objekt musst du fillStyle oder strokeStyle zuweisen und danach eine Form füllen oder nachzeichnen. Die Koordinaten beziehen sich auf das Koordinatensystem des Canvas, nicht auf die gezeichnete Form. Es gilt also die Transformation, die beim Zeichnen aktiv ist.

Parameter

Name Typ Default Beschreibung
$startAngle Pflicht number Winkel im Bogenmaß, bei dem der Verlauf beginnt (Offset 0). 0 = rechts (3 Uhr), positive Werte drehen im Uhrzeigersinn.
$x Pflicht number x-Koordinate des Mittelpunkts, um den sich der Verlauf dreht.
$y Pflicht number y-Koordinate des Mittelpunkts, um den sich der Verlauf dreht.

Rückgabewert

Typ
CanvasGradient
Beschreibung
Ein CanvasGradient-Objekt, das zunächst keine Farbstopps enthält. Die Farben fügst du mit addColorStop() hinzu.

Beispiele

Farbkreis (Hue-Wheel) zeichnen

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');

const cx = canvas.width / 2;
const cy = canvas.height / 2;
const radius = Math.min(cx, cy) - 10;

// Verlauf beginnt oben (12 Uhr)
const gradient = ctx.createConicGradient(-Math.PI / 2, cx, cy);

// Alle Farbtöne von 0° bis 360°
for (let hue = 0; hue <= 360; hue += 60) {
  gradient.addColorStop(hue / 360, `hsl(${hue}, 100%, 50%)`);
}

ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
ctx.fill();

Fortschrittsring mit Verlaufsfarbe

const ctx = document.querySelector('#progress').getContext('2d');

const drawProgress = (percent) => {
  const { width, height } = ctx.canvas;
  const cx = width / 2;
  const cy = height / 2;
  const start = -Math.PI / 2;
  const end = start + (Math.PI * 2 * percent) / 100;

  ctx.clearRect(0, 0, width, height);

  const gradient = ctx.createConicGradient(start, cx, cy);
  gradient.addColorStop(0, '#22c55e');
  gradient.addColorStop(0.5, '#eab308');
  gradient.addColorStop(1, '#ef4444');

  ctx.lineWidth = 16;
  ctx.lineCap = 'round';
  ctx.strokeStyle = gradient;
  ctx.beginPath();
  ctx.arc(cx, cy, 60, start, end);
  ctx.stroke();

  ctx.fillStyle = '#111';
  ctx.font = 'bold 24px sans-serif';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(`${percent} %`, cx, cy);
};

drawProgress(72);

Schachbrett-/Tortenmuster mit harten Farbstopps

const ctx = document.querySelector('canvas').getContext('2d');

const gradient = ctx.createConicGradient(0, 100, 100);
// Gleiche Offsets für zwei Farben ergeben harte Kanten
gradient.addColorStop(0, '#3b82f6');
gradient.addColorStop(0.25, '#3b82f6');
gradient.addColorStop(0.25, '#f97316');
gradient.addColorStop(0.5, '#f97316');
gradient.addColorStop(0.5, '#3b82f6');
gradient.addColorStop(0.75, '#3b82f6');
gradient.addColorStop(0.75, '#f97316');
gradient.addColorStop(1, '#f97316');

ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 200);

Feature-Erkennung mit Fallback

const ctx = document.querySelector('canvas').getContext('2d');

const makeFill = (x, y) => {
  if (typeof ctx.createConicGradient === 'function') {
    const g = ctx.createConicGradient(0, x, y);
    g.addColorStop(0, 'red');
    g.addColorStop(1, 'blue');
    return g;
  }
  // Fallback: radialer Verlauf
  const g = ctx.createRadialGradient(x, y, 0, x, y, 100);
  g.addColorStop(0, 'red');
  g.addColorStop(1, 'blue');
  return g;
};

ctx.fillStyle = makeFill(100, 100);
ctx.fillRect(0, 0, 200, 200);
console.log(ctx.fillStyle instanceof CanvasGradient);
true

// Wichtig · Fallstricke

  • Bogenmaß statt Grad: startAngle wird im Bogenmaß angegeben. Grad rechnest du mit deg * Math.PI / 180 um. Anders als bei CSS conic-gradient() liegt der Winkel 0 rechts und nicht oben. Für einen Start bei 12 Uhr verwendest du -Math.PI / 2.
  • Sichtbare Naht: Unterscheiden sich die Farben bei Offset 0 und 1, entsteht am Startwinkel eine harte Kante. Für nahtlose Übergänge setzt du bei 1 dieselbe Farbe wie bei 0.
  • Nicht endliche Werte: Ist ein Argument NaN oder Infinity, wird kein Verlauf gezeichnet. Fehlen Argumente, wird ein TypeError geworfen.
  • Transformationen: Der Verlauf ist an das Koordinatensystem gebunden, das beim Zeichnen aktiv ist, und nicht an die Form. Wenn du die Form verschiebst, musst du den Mittelpunkt anpassen oder mit translate() arbeiten.
  • Kompatibilität: Die Methode ist erst seit 2023 in allen großen Browsern verfügbar (Chrome/Edge 99, Safari 16.1, Firefox 112). Ältere Browser unterstützen sie nicht, deshalb solltest du bei Bedarf mit typeof ctx.createConicGradient === 'function' prüfen. Die Methode gibt es auch in OffscreenCanvasRenderingContext2D, also auch in Web Workern.
  • Leistung: Wenn Mittelpunkt und Farben gleich bleiben, solltest du das Verlaufsobjekt einmal erzeugen und wiederverwenden, statt es in jedem Animationsframe neu anzulegen.