Canvas wijzerplaat
Deel II - Teken een wijzerplaat
De klok heeft een wijzerplaat nodig. Maak een JavaScript-functie om een wijzerplaat te tekenen:
javascript:
function drawClock() {
drawFace(ctx, radius);
}
function drawFace(ctx, radius) {
var grad;
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = 'white';
ctx.fill();
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.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();
}
Code uitgelegd
Maak een drawFace()-functie voor het tekenen van de wijzerplaat:
function drawClock() {
drawFace(ctx, radius);
}
function drawFace(ctx, radius) {
}
Teken de witte cirkel:
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = 'white';
ctx.fill();
Maak een radiaal verloop (95% en 105% van de oorspronkelijke klokradius):
grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05);
Maak 3 kleurstops, overeenkomend met de binnenste, middelste en buitenste rand van de boog:
grad.addColorStop(0, '#333');
grad.addColorStop(0.5, 'white');
grad.addColorStop(1, '#333');
De kleurstops creëren een 3D-effect.
Definieer het verloop als de streekstijl van het tekenobject:
ctx.strokeStyle = grad;
Definieer de lijnbreedte van het tekenobject (10% van de straal):
ctx.lineWidth = radius * 0.1;
Teken de cirkel:
ctx.stroke();
Teken het klokcentrum:
ctx.beginPath();
ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
ctx.fillStyle = '#333';
ctx.fill();