Angka Jam Canvas

Bagian kedua - Gambar jam

Jam memerlukan jam. Buat fungsi JavaScript untuk menggambar 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();
}

Coba sendiri

Pengertian kode

Buat fungsi drawFace() untuk menggambar jam:

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

Gambar lingkaran putih:

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

Buat gelombang radial (95% dan 105% radius jam asli):

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

Buat 3 pita, masing-masing berkorban bagian luar, tengah, dan luar lingkaran:

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

Petunjuk: Tiga pita ini dapat menghasilkan efek 3D.

Tentukan gelombang transisi sebagai gaya pengecatan objek pereka:

ctx.strokeStyle = grad;

Tentukan lebar garis objek pereka (10% dari radius):

ctx.lineWidth = radius * 0.1;

Gambar lingkaran:

ctx.stroke();

Menarik 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