Digit Jam Canvas

Bagian kedua - menggambar mukanya jam

Jam memerlukan mukanya jam. Bina fungsi JavaScript untuk menggambar mukanya jam:

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();
}

cuba sendiri

penerangan kod

membentuk fungsi drawFace() untuk menggambar mukanya jam:

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

menggambar bulatan putih:

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

membentuk pelbagai warna jarak (95% dan 105% radius asal jam):

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

membentuk tiga paku warna, masing-masing sepadan pinggir, tengah dan luar serupa:

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

Peringatan: tiga paku warna ini boleh membentuk kesan 3D.

mendefinikan pelbagai warna grad untuk gaya tebal:

ctx.strokeStyle = grad;

mengdefinikan lebar garis objek pereka (10% radius):

ctx.lineWidth = radius * 0.1;

menggambar bulatan:

ctx.stroke();

menyatakan pusat jam:

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

Lihat Juga:

Panduan Lengkap Canvas CodeW3C.com