


JS&canvas 7/7 — Итоги
Завершаем создание часиков — придаем оттенок фону, и добавляем подписи. А также дальнейшие возможные пути развития.
День 7
За 7 дней — был написан небольшой плагин на Javascript, с помощью которого мы познакомились с некоторыми основными моментами работы с элементом canvas.
Осталось только довести часы до подобия логотипа к данному курсу, для чего модифицируем метод рисования корпуса часов drawClockBody()
До этого я не упоминал, что цвет рисования и заливки можно указывать не только с помощью html имен цветов, или указания их rgb представления в hex виде (например #b6b6b6, #fff), но также доступно использование функций из CSS — rgb(r,g,b) и ее коллеги rgba(r,g,b,a), которая позволяет задавать прозрачность. Соответственно уже знакомое указание стиля рисования будет выглядеть тогда следующим образом:
1 |
ctx.strokeStyle = 'rgba(250,250,250,0.8)'; |
Указав новые настройки рисования выведем бледненький серый прозрачный фон для фона часов, а также опормим подпись на нем:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function drawClockBody(){ ctx.save(); ctx.beginPath(); ctx.lineWidth = "12"; ctx.strokeStyle = "#3388DE"; ctx.arc(cX,cY,R,0,Math.PI*2); ctx.fillStyle = 'rgba(250,250,250,0.8)'; ctx.fill(); ctx.fillStyle = 'rgba(51,136,222,0.8)'; ctx.font = '28px Arial black'; ctx.fillText('canvas',cX - 55, cY + R*0.25); ctx.font = '30px Arial black'; ctx.fillStyle = 'rgba(51,136,222,0.3)'; ctx.fillText('JAVASCRIPT',cX - 103,cY + R*0.5); ctx.stroke(); ctx.restore(); } |
На этом моя разработка часов с целью знакомства с canvas закончилась — конечный результат получен. Что еще можно было бы улучшить и дополнить в получившемся плагине — это позволить получать настройки извне, чтобы создание часов было не просто
1 |
var myclock = new Myclock() |
А было что-то вроде такого
1 2 3 4 5 6 7 8 |
var myclock = new Myclock({ id : clock, frameColor: #3388DE, clockSize: 1, showArrows: [hours, minutes], smoothMoving: false //... и т.д. }); |
Но для искусственной задачи как эта, в такой мощной параметризации нет особого смысла, разве что в целях обучения Javascript’у на очередном рабочем примере, ведь чтобы учиться программировать — нужно программировать.
Несколько отличающийся вариант реализации мною этих же часов можно найти здесь — cdpn.io/kiHoy.
Код страницы day7.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
<!DOCTYPE html> <html> <head> <title>День 7 - </title> <script src="jquery.js"></script> </head> <body> <canvas id="clock"></canvas> <script> var Myclock = function(){ var clock,ctx,cX,cY,R; var buffer = null; var now = new Date(); var time = { ms:now.getMilliseconds(), s:now.getSeconds(), m:now.getMinutes(), h:now.getHours() } var position = { sec:{ x:null, y:null }, min:{ x:null, y:null }, hrs:{ x:null, y:null } } function drawClockFace(){ ctx.save(); ctx.strokeStyle = '#222'; ctx.fillStyle = "#222"; for(var i = 1;i<61;i++){ ctx.beginPath(); var angle = i * Math.PI / 30 - Math.PI / 2; var dx = Math.cos(angle) * R; var dy = Math.sin(angle) * R; if(i%15 == 0){ ctx.font = '19px Tahoma'; ctx.textAlign = 'center'; ctx.textBaseline = "middle"; ctx.fillText(i/5, cX + dx*0.9, cY + dy*0.9); }else if(i%5 == 0){ ctx.arc(cX + 0.9 * dx, cY + 0.9 * dy,1.5,360,0) ctx.fill(); }else{ ctx.arc(cX + 0.9 * dx, cY + 0.9 * dy,0.5,360,0) ctx.fill(); } ctx.stroke(); } ctx.restore(); } function drawClockBody(){ ctx.save(); ctx.beginPath(); ctx.lineWidth = "12"; ctx.strokeStyle = "#3388DE"; ctx.arc(cX,cY,R,0,Math.PI*2); ctx.fillStyle = 'rgba(250,250,250,0.8)'; ctx.fill(); ctx.fillStyle = 'rgba(51,136,222,0.8)'; ctx.font = '28px Arial black'; ctx.fillText('canvas',cX - 55, cY + R*0.25); ctx.font = '30px Arial black'; ctx.fillStyle = 'rgba(51,136,222,0.3)'; ctx.fillText('JAVASCRIPT',cX - 103,cY + R*0.5); ctx.stroke(); ctx.restore(); } function drawSeconds(){ ctx.save(); angleS = (time.s + time.ms * 0.001) * Math.PI/30 - Math.PI/2; position.sec.x = cX + Math.cos(angleS) * R * 0.88; position.sec.y = cY + Math.sin(angleS) * R * 0.88; ctx.beginPath(); ctx.moveTo(cX,cY); ctx.lineTo(position.sec.x,position.sec.y); ctx.stroke(); ctx.restore(); } function drawMinutes(){ ctx.save(); angleM = (time.m + time.s/60) * Math.PI/30 - Math.PI/2; position.min.x = cX + Math.cos(angleM) * R * 0.66; position.min.y = cY + Math.sin(angleM) * R * 0.66; ctx.beginPath(); ctx.lineWidth = 4; ctx.lineCap = 'round'; ctx.moveTo(cX,cY); ctx.lineTo(position.min.x,position.min.y); ctx.stroke(); ctx.restore(); } function drawHours(){ ctx.save(); angleH = (time.h + time.m/60) * Math.PI/6 - Math.PI/2; position.hrs.x = cX + Math.cos(angleH) * R * 0.33; position.hrs.y = cY + Math.sin(angleH) * R * 0.33; ctx.beginPath(); ctx.lineWidth = 9; ctx.lineCap = 'round'; ctx.moveTo(cX,cY); ctx.lineTo(position.hrs.x,position.hrs.y); ctx.stroke(); ctx.restore(); } function init(canvasId){ if (canvasId && canvasId.length > 0) { clock = document.getElementById(canvasId); if(clock === null){ console.error('Myclock init error: элемент canvas с id = "' + canvasId + '" не найден'); return -1; } }else{ console.error('Myclock init error: не задан идентификатор холста'); return -1; } clock.width = 400; clock.height = 400; ctx = clock.getContext('2d'); cX = clock.offsetLeft + clock.width / 2; cY = clock.offsetTop + clock.height /2; R = 180; drawClockBody(); drawClockFace(); buffer = ctx.getImageData(0, 0, clock.width, clock.height); //setInterval(update,10); } function update(){ ctx.translate(0.5,0,0,0.5,0,0); now = new Date(2013,10,07,10,12,3); time.ms = now.getMilliseconds(); time.s = now.getSeconds(); time.m = now.getMinutes(); time.h = now.getHours(); ctx.putImageData(buffer,0,0); drawSeconds(); drawMinutes(); drawHours(); } //public this.init = init; this.update = update; } var myclock = new Myclock(); myclock.init("clock"); </script> </body> </html> |
Оставь комментарий!
One thought on “JS&canvas 7/7 — Итоги”
Добавить комментарий
Для отправки комментария вам необходимо авторизоваться.
Огромное спасибо за уроки! Очень помогли