Canvas ur tal

Del 2 - Tegning af urskive

Klokken har brug for en urskive. Opret en JavaScript-funktion til at tegne urskiven:

JavaScript:

function drawClock() {
  drawFace(ctx, radius);
}
function drawFace(ctx, radius) {
  const grad = ctx.createRadialGradient(0, 0 ,radius * 0.95, 0, 0, radius * 1.05);
  grad.addColorStop(0, '#333');
  grad.addColorStop(0.5, 'white');
  grad.addColorStop(1, '#333');
  ctx.beginPath();
  ctx.arc(0, 0, radius, 0, 2 * Math.PI);
  ctx.fillStyle = 'white';
  ctx.fill();
  ctx.strokeStyle = grad;
  ctx.lineWidth = radius*0.1;
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
  ctx.fillStyle = '#333';
  ctx.fill();
}

Prøv det selv

Kodeforklaring

Opret en drawFace() funktion til at tegne urskiven:

function drawClock() {
  drawFace(ctx, radius);
}
function drawFace(ctx, radius) {
}

Tegning af hvid cirkel:

ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = 'white';
ctx.fill();

Opret en radial overgang (95% og 105% af original klokkes radius):

grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05);

Opret 3 farvekoder, der svarer til cirkelens indre kant, midterkant og ydre kant:

grad.addColorStop(0, '#333');
grad.addColorStop(0.5, 'white');
grad.addColorStop(1, '#333');

Tip: Disse tre farvekoder kan skabe et 3D-effekt.

Definer overgangsfarven som tegneobjektets pennefarve:

ctx.strokeStyle = grad;

Definer linjestørrelsen for tegneobjektet (10% af radiusen):

ctx.lineWidth = radius * 0.1;

Tegning af cirkel:

ctx.stroke();

Tegning af klokkescenter:

ctx.beginPath();
ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
ctx.fillStyle = '#333';
ctx.fill();

Se også:

Det fulde Canvas reference manual på CodeW3C.com