Как я могу заставить идти стрелки в часах?
Когда вы открываете страницу, секундная стрелка направлена вверх, и только после второго показа, начинает идти. Мне нужно запустить их без этой секунды, но я не могу изменить setInterval(1000), и у меня нет идей о том, как это исправить. Помогите, пожалуйста. setInterval (moveArrows, 1000) находится в конце кода.
const svg = document.getElementById('svg');
console.log(svg);
const svg_xnls = 'http://www.w3.org/2000/svg';
//если не найдет аттрибутов width || height, то вернет null
const width = parseFloat(svg.getAttributeNS(null, 'width'));
const height = parseFloat(svg.getAttributeNS(null, 'height'));
// радиус часиков (большого желтого круга)
const clockRadius = width / 2;
// радиус кружочков с цифрами часов времени
const radius = 0.8 * clockRadius;
//создаю переменные половин ширины и высоты
let widthHalf = width / 2;
let heightHalf = height / 2;
// создаю функцию желтого круга
function drawClockBody(clock) {
// создаю круг
let clockBodyStyle = document.createElementNS(svg_xnls, 'circle');
// задаю атрибуты/стили (с - center)
clockBodyStyle.setAttributeNS(null, 'cx', widthHalf);
clockBodyStyle.setAttributeNS(null, 'cy', heightHalf);
clockBodyStyle.setAttributeNS(null, 'r', widthHalf);
clockBodyStyle.setAttributeNS(null, 'fill', '#fcca66');
clockBodyStyle.setAttributeNS(null, 'stroke', 'none');
//рисую круг в HTML
svg.appendChild(clockBodyStyle);
}
drawClockBody();
// можно было сделать двумя функциями
// создаю функцию для кружочков с цифрами
function drawHours(hour, hourValue) {
// градус угла
const angel = 30;
for (let i = 1; i <= 12; i++) {
// рисую круг
let hourCircle = document.createElementNS(svg_xnls, 'circle');
svg.appendChild(hourCircle);
// раставляю кружочки по кругу
let angelRadian = (angel * i * Math.PI) / 180;
//считаю центр кружочка относительно тела часов
let hourCenterX = clockRadius + radius * Math.sin(angelRadian);
let hourCenterY = clockRadius - radius * Math.cos(angelRadian);
// задаю атрибуты/стили
hourCircle.setAttributeNS(null, 'cx', hourCenterX);
hourCircle.setAttributeNS(null, 'cy', hourCenterY);
hourCircle.setAttributeNS(null, 'r', 40);
hourCircle.setAttributeNS(null, 'fill', '#48b382');
hourCircle.setAttributeNS(null, 'stroke', 'none');
// cоздаю текс
let text = document.createElementNS(svg_xnls, 'text');
svg.appendChild(text);
// контент текста равен i
text.textContent = i;
// задаю атрибуты/стили
text.setAttributeNS(null, 'x', hourCenterX);
text.setAttributeNS(null, 'y', hourCenterY + 13);
text.style.width = '80';
text.style.height = '80';
text.style.fontSize = '40';
text.style.fontWeight = 'bold';
text.style.textAnchor = 'middle';
}
}
drawHours();
// создаю функцию стрелок
function drawArrows(hour_arrow, minute_arrow, second_aqrrow) {
// создаю стрелку часов
const hourArrow = document.createElementNS(svg_xnls, 'line');
// задаю атрибуты/стили
hourArrow.setAttributeNS(null, 'x1', widthHalf);
hourArrow.setAttributeNS(null, 'x2', widthHalf);
hourArrow.setAttributeNS(null, 'y1', widthHalf);
hourArrow.setAttributeNS(null, 'y2', 100);
hourArrow.setAttributeNS(null, 'stroke', '#000000');
hourArrow.setAttributeNS(null, 'stroke-linecap', 'round');
hourArrow.setAttributeNS(null, 'stroke-width', 6);
hourArrow.setAttributeNS(null, 'id', 'hours');
// рисую стрелку
svg.appendChild(hourArrow);
// создаю стрелку часов
const minuteArrow = document.createElementNS(svg_xnls, 'line');
// задаю атрибуты/стили
minuteArrow.setAttributeNS(null, 'x1', widthHalf);
minuteArrow.setAttributeNS(null, 'x2', widthHalf);
minuteArrow.setAttributeNS(null, 'y1', widthHalf);
minuteArrow.setAttributeNS(null, 'y2', 60);
minuteArrow.setAttributeNS(null, 'stroke', '#0000ff');
minuteArrow.setAttributeNS(null, 'stroke-linecap', 'round');
minuteArrow.setAttributeNS(null, 'stroke-width', 4);
minuteArrow.setAttributeNS(null, 'id', 'minutes');
// рисую стрелку
svg.appendChild(minuteArrow);
// создаю стрелку часов
const secondArrow = document.createElementNS(svg_xnls, 'line');
// задаю атрибуты/стили
secondArrow.setAttributeNS(null, 'x1', widthHalf);
secondArrow.setAttributeNS(null, 'x2', widthHalf);
secondArrow.setAttributeNS(null, 'y1', widthHalf);
secondArrow.setAttributeNS(null, 'y2', 40);
secondArrow.setAttributeNS(null, 'stroke', '#ff2000');
secondArrow.setAttributeNS(null, 'stroke-linecap', 'round');
secondArrow.setAttributeNS(null, 'stroke-width', 2);
secondArrow.setAttributeNS(null, 'id', 'seconds');
// рисую стрелку
svg.appendChild(secondArrow);
}
drawArrows();
// создаю элемент текста
const textTime = document.createElementNS(svg_xnls, 'text');
svg.appendChild(textTime);
// задаю стили
textTime.setAttributeNS(null, 'x', 300);
textTime.setAttributeNS(null, 'y', 200);
textTime.setAttributeNS(null, 'id', 'text-time');
textTime.style.fontSize = '2rem';
textTime.style.fontWeight = 'bold';
textTime.style.textAnchor = 'middle';
window.onload = function operation() {
function moveArrows() {
const now = new Date();
let seconds = now.getSeconds() * 6;
// console.log(seconds);
let minutes = now.getMinutes() * 6;
// console.log(minutes);
// задаю так часы, чтобы они не перескакивали с часа на час, а плавно шли от часа к часу
let hours = (now.getHours() + now.getMinutes() / 60 + now.getSeconds() * 3600) * 30;
// беру стрелки по Id, чтоб потом передать им анимацию
let hoursStyle = document.getElementById('hours');
let minutesStyle = document.getElementById('minutes');
let secondsStyle = document.getElementById('seconds');
// задаю анимацию
secondsStyle.setAttributeNS(null, 'transform', 'rotate(' + seconds + ' 300 300)');
minutesStyle.setAttributeNS(null, 'transform', 'rotate(' + minutes + ' 300 300)');
hoursStyle.setAttributeNS(null, 'transform', 'rotate(' + hours + ' 300 300)');
// создаю функцию в которой буду показывать время в виде циферок
function showTime(time) {
// делаю проверку для красоты, (const textHour = now.getHours() - работает одинаково)
const textHour = (now.getHours() < 10) ? ('0' + now.getHours()) : (now.getHours());
const textMinutes = (now.getMinutes() < 10) ? ('0' + now.getMinutes()) : (now.getMinutes());
const textSeconds = (now.getSeconds() < 10) ? ('0' + now.getSeconds()) : (now.getSeconds());
// беру по id мой текст и вставляю туда время
document.getElementById("text-time").textContent = textHour + ':' + textMinutes + ':' + textSeconds;
}
showTime();
}
setInterval(moveArrows, 1000);
};
Свободный перевод вопроса How can i make arrows go in clock? от участника @10100011001.
Ответы (2 шт):
Просто вызовите функцию moveArrows() во время инициализации.
drawArrows();
moveArrows();
const svg = document.getElementById('svg');
//console.log(svg);
const svg_xnls = 'http://www.w3.org/2000/svg';
//если не найдет аттрибутов width || height, то вернет null
const width = parseFloat(svg.getAttributeNS(null, 'width'));
const height = parseFloat(svg.getAttributeNS(null, 'height'));
// радиус часиков (большого желтого круга)
const clockRadius = width / 2;
// радиус кружочков с цифрами часов времени
const radius = 0.8 * clockRadius;
//создаю переменные половин ширины и высоты
let widthHalf = width / 2;
let heightHalf = height / 2;
// создаю функцию желтого круга
function drawClockBody(clock) {
// создаю круг
let clockBodyStyle = document.createElementNS(svg_xnls, 'circle');
// задаю атрибуты/стили (с - center)
clockBodyStyle.setAttributeNS(null, 'cx', widthHalf);
clockBodyStyle.setAttributeNS(null, 'cy', heightHalf);
clockBodyStyle.setAttributeNS(null, 'r', widthHalf);
clockBodyStyle.setAttributeNS(null, 'fill', '#fcca66');
clockBodyStyle.setAttributeNS(null, 'stroke', 'none');
//рисую круг в HTML
svg.appendChild(clockBodyStyle);
}
drawClockBody();
// можно было сделать двумя функциями
// создаю функцию для кружочков с цифрами
function drawHours(hour, hourValue) {
// градус угла
const angel = 30;
for (let i = 1; i <= 12; i++) {
// рисую круг
let hourCircle = document.createElementNS(svg_xnls, 'circle');
svg.appendChild(hourCircle);
// раставляю кружочки по кругу
let angelRadian = (angel * i * Math.PI) / 180;
//считаю центр кружочка относительно тела часов
let hourCenterX = clockRadius + radius * Math.sin(angelRadian);
let hourCenterY = clockRadius - radius * Math.cos(angelRadian);
// задаю атрибуты/стили
hourCircle.setAttributeNS(null, 'cx', hourCenterX);
hourCircle.setAttributeNS(null, 'cy', hourCenterY);
hourCircle.setAttributeNS(null, 'r', 40);
hourCircle.setAttributeNS(null, 'fill', '#48b382');
hourCircle.setAttributeNS(null, 'stroke', 'none');
// cоздаю текс
let text = document.createElementNS(svg_xnls, 'text');
svg.appendChild(text);
// контент текста равен i
text.textContent = i;
// задаю атрибуты/стили
text.setAttributeNS(null, 'x', hourCenterX);
text.setAttributeNS(null, 'y', hourCenterY + 13);
text.style.width = '80';
text.style.height = '80';
text.style.fontSize = '40';
text.style.fontWeight = 'bold';
text.style.textAnchor = 'middle';
}
}
drawHours();
// создаю функцию стрелок
function drawArrows(hour_arrow, minute_arrow, second_aqrrow) {
// создаю стрелку часов
const hourArrow = document.createElementNS(svg_xnls, 'line');
// задаю атрибуты/стили
hourArrow.setAttributeNS(null, 'x1', widthHalf);
hourArrow.setAttributeNS(null, 'x2', widthHalf);
hourArrow.setAttributeNS(null, 'y1', widthHalf);
hourArrow.setAttributeNS(null, 'y2', 100);
hourArrow.setAttributeNS(null, 'stroke', '#000000');
hourArrow.setAttributeNS(null, 'stroke-linecap', 'round');
hourArrow.setAttributeNS(null, 'stroke-width', 6);
hourArrow.setAttributeNS(null, 'id', 'hours');
// рисую стрелку
svg.appendChild(hourArrow);
// создаю стрелку часов
const minuteArrow = document.createElementNS(svg_xnls, 'line');
// задаю атрибуты/стили
minuteArrow.setAttributeNS(null, 'x1', widthHalf);
minuteArrow.setAttributeNS(null, 'x2', widthHalf);
minuteArrow.setAttributeNS(null, 'y1', widthHalf);
minuteArrow.setAttributeNS(null, 'y2', 60);
minuteArrow.setAttributeNS(null, 'stroke', '#0000ff');
minuteArrow.setAttributeNS(null, 'stroke-linecap', 'round');
minuteArrow.setAttributeNS(null, 'stroke-width', 4);
minuteArrow.setAttributeNS(null, 'id', 'minutes');
// рисую стрелку
svg.appendChild(minuteArrow);
// создаю стрелку часов
const secondArrow = document.createElementNS(svg_xnls, 'line');
// задаю атрибуты/стили
secondArrow.setAttributeNS(null, 'x1', widthHalf);
secondArrow.setAttributeNS(null, 'x2', widthHalf);
secondArrow.setAttributeNS(null, 'y1', widthHalf);
secondArrow.setAttributeNS(null, 'y2', 40);
secondArrow.setAttributeNS(null, 'stroke', '#ff2000');
secondArrow.setAttributeNS(null, 'stroke-linecap', 'round');
secondArrow.setAttributeNS(null, 'stroke-width', 2);
secondArrow.setAttributeNS(null, 'id', 'seconds');
// рисую стрелку
svg.appendChild(secondArrow);
}
function moveArrows() {
const now = new Date();
let seconds = now.getSeconds() * 6;
// console.log(seconds);
let minutes = now.getMinutes() * 6;
// console.log(minutes);
// задаю так часы, чтобы они не перескакивали с часа на час, а плавно шли от часа к часу
let hours = (now.getHours() + now.getMinutes() / 60 + now.getSeconds() * 3600) * 30;
// беру стрелки по Id, чтоб потом передать им анимацию
let hoursStyle = document.getElementById('hours');
let minutesStyle = document.getElementById('minutes');
let secondsStyle = document.getElementById('seconds');
// задаю анимацию
secondsStyle.setAttributeNS(null, 'transform', 'rotate(' + seconds + ' ' + widthHalf + ' ' + heightHalf + ')');
minutesStyle.setAttributeNS(null, 'transform', 'rotate(' + minutes + ' ' + widthHalf + ' ' + heightHalf + ')');
hoursStyle.setAttributeNS(null, 'transform', 'rotate(' + hours + ' ' + widthHalf + ' ' + heightHalf + ')');
// создаю функцию в которой буду показывать время в виде циферок
function showTime(time) {
// делаю проверку для красоты, (const textHour = now.getHours() - работает одинаково)
const textHour = (now.getHours() < 10) ? ('0' + now.getHours()) : (now.getHours());
const textMinutes = (now.getMinutes() < 10) ? ('0' + now.getMinutes()) : (now.getMinutes());
const textSeconds = (now.getSeconds() < 10) ? ('0' + now.getSeconds()) : (now.getSeconds());
// беру по id мой текст и вставляю туда время
document.getElementById("text-time").textContent = textHour + ':' + textMinutes + ':' + textSeconds;
}
showTime();
}
// создаю элемент текста
const textTime = document.createElementNS(svg_xnls, 'text');
svg.appendChild(textTime);
// задаю стили
textTime.setAttributeNS(null, 'x', 300);
textTime.setAttributeNS(null, 'y', 200);
textTime.setAttributeNS(null, 'id', 'text-time');
textTime.style.fontSize = '2rem';
textTime.style.fontWeight = 'bold';
textTime.style.textAnchor = 'middle';
drawArrows();
moveArrows();
window.onload = function operation() {
setInterval(moveArrows, 1000);
};
<svg id="svg" width="300" height="300">
</svg>
Свободный перевод ответа How can i make arrows go in clock? от участника @Paul LeBeau.
На основе ответа от @Paul LeBeau.
Чуть подправил, добавил немного фишек, контур стрелки при чётных наведениях, подсветка, озвучка, пару овалов с градиентом ну и т.п.
В общем мелочи, но приятно было повозиться )
Спасибо за интересную задачу.
const svg = document.getElementById('svg');
//console.log(svg);
const svg_xnls = 'http://www.w3.org/2000/svg';
//если не найдет аттрибутов width || height, то вернет null
const width = parseFloat(svg.getAttributeNS(null, 'width'));
const height = parseFloat(svg.getAttributeNS(null, 'height'));
// радиус часиков (большого желтого круга)
const clockRadius = width / 2;
// радиус кружочков с цифрами часов времени
const radius = 0.8 * clockRadius;
//создаю переменные половин ширины и высоты
let widthHalf = width / 2;
let heightHalf = height / 2;
// создаю функцию желтого круга
function drawClockBody(clock) {
// создаю круг
let clockBodyStyle = document.createElementNS(svg_xnls, 'circle');
// задаю атрибуты/стили (с - center)
clockBodyStyle.setAttributeNS(null, 'cx', widthHalf);
clockBodyStyle.setAttributeNS(null, 'cy', heightHalf);
clockBodyStyle.setAttributeNS(null, 'r', widthHalf);
clockBodyStyle.setAttributeNS(null, 'fill', '#413f3f');
clockBodyStyle.setAttributeNS(null, 'stroke', 'gold');
clockBodyStyle.setAttributeNS(null, 'stroke-width', '2%');
//рисую круг в HTML
svg.appendChild(clockBodyStyle);
}
drawClockBody();
//Добавим кнопку
let minsec = 0;
function addButton() {
let mmain = document.createElement('div');
mmain.style.width = '100%';
let but = document.createElement('button');
but.id = 'butt';
but.innerText = 'Озвучить секунды';
but.style.marginLeft = '5px';
but.style.marginTop = '20px';
but.style.height = '35px';
but.style.backgroundColor = 'gold';
but.style.width = '150px';
but.style.fontSize = '12';
but.style.fontWeight = '600';
but.style.border = '4px double black';
mmain.appendChild(but);
let but1 = document.createElement('button');
but1.id = 'butt1';
but1.innerText = 'Точное время';
but1.style.height = '35px';
but1.style.width = '150px';
but1.style.backgroundColor = 'gold';
but1.style.fontSize = '12';
but1.style.fontWeight = '600';
but1.style.border = '4px double black';
mmain.appendChild(but1);
document.body.appendChild(mmain);
but.onclick = function () {
minsec = 0;
};
but1.onclick = function () {
let tttime = new Date();
var HmmTime = function(number, titles) {
var cases = [2, 0, 1, 1, 1, 2];
return titles[
(number % 100 > 4 && number % 100 < 20)
?
2
:
cases[(number % 10 < 5) ? number % 10 : 5]
];
};
tttime = 'Точное время '+tttime.getHours()+' '+HmmTime(tttime.getHours(), ['час', 'часа', 'часов'])+' '+tttime.getMinutes()+ ' ' +HmmTime(tttime.getMinutes(), ['минута', 'минуты', 'минут'])+' и '+tttime.getSeconds()+' '+HmmTime(tttime.getSeconds(), ['секунда', 'секунды', 'секунд']);
minsec = 1;
var lang = "ru-RU";
var synth = window.speechSynthesis,
voice = '',
supportedVoices = [];
if (0 === supportedVoices.length) {
var voices = synth.getVoices();
}
for (var i = 0; i < voices.length; i++) {
if (lang == voices[i].lang) {
voice = voices[i];
}
}
var utterThis = new SpeechSynthesisUtterance(tttime);
utterThis.voice = voice;
synth.speak(utterThis);
}
}
addButton();
// можно было сделать двумя функциями
// создаю функцию для кружочков с цифрами
function drawHours(hour, hourValue) {
// градус угла
const angel = 30;
for (let i = 1; i <= 12; i++) {
// рисую круг
let hourCircle = document.createElementNS(svg_xnls, 'circle');
svg.appendChild(hourCircle);
// раставляю кружочки по кругу
let angelRadian = (angel * i * Math.PI) / 180;
//считаю центр кружочка относительно тела часов
let hourCenterX = clockRadius + radius * Math.sin(angelRadian);
let hourCenterY = clockRadius - radius * Math.cos(angelRadian);
// задаю атрибуты/стили
hourCircle.setAttributeNS(null, 'cx', hourCenterX);
hourCircle.setAttributeNS(null, 'cy', hourCenterY);
hourCircle.setAttributeNS(null, 'r', 21);
hourCircle.setAttributeNS(null, 'fill', '#74797a');
hourCircle.setAttributeNS(null, 'stroke', 'gold');
hourCircle.setAttributeNS(null, 'stroke-width', '1px');
hourCircle.setAttributeNS(null, 'name', 'bz');
// cоздаю текс
let text = document.createElementNS(svg_xnls, 'text');
svg.appendChild(text);
// контент текста равен i
text.textContent = i;
// задаю атрибуты/стили
text.setAttributeNS(null, 'x', hourCenterX);
text.setAttributeNS(null, 'y', hourCenterY + 13);
text.style.width = '80';
text.style.height = '80';
text.style.fontSize = '40';
text.style.fontWeight = 'bold';
text.style.textAnchor = 'middle';
}
}
drawHours();
// создаю функцию стрелок
function drawArrows(hour_arrow, minute_arrow, second_aqrrow) {
// создаю стрелку часов
const hourArrow = document.createElementNS(svg_xnls, 'line');
// задаю атрибуты/стили
hourArrow.setAttributeNS(null, 'x1', widthHalf);
hourArrow.setAttributeNS(null, 'x2', widthHalf);
hourArrow.setAttributeNS(null, 'y1', widthHalf);
hourArrow.setAttributeNS(null, 'y2', 100);
hourArrow.setAttributeNS(null, 'stroke', '#000000');
hourArrow.setAttributeNS(null, 'stroke-linecap', 'round');
hourArrow.setAttributeNS(null, 'stroke-width', 6);
hourArrow.setAttributeNS(null, 'id', 'hours');
// рисую стрелку
svg.appendChild(hourArrow);
// создаю стрелку часов
const minuteArrow = document.createElementNS(svg_xnls, 'line');
// задаю атрибуты/стили
minuteArrow.setAttributeNS(null, 'x1', widthHalf);
minuteArrow.setAttributeNS(null, 'x2', widthHalf);
minuteArrow.setAttributeNS(null, 'y1', widthHalf);
minuteArrow.setAttributeNS(null, 'y2', 60);
minuteArrow.setAttributeNS(null, 'stroke', '#0000ff');
minuteArrow.setAttributeNS(null, 'stroke-linecap', 'round');
minuteArrow.setAttributeNS(null, 'stroke-width', 4);
minuteArrow.setAttributeNS(null, 'id', 'minutes');
// рисую стрелку
svg.appendChild(minuteArrow);
// создаю стрелку часов
const secondArrow = document.createElementNS(svg_xnls, 'line');
// задаю атрибуты/стили
secondArrow.setAttributeNS(null, 'x1', widthHalf);
secondArrow.setAttributeNS(null, 'x2', widthHalf);
secondArrow.setAttributeNS(null, 'y1', widthHalf);
secondArrow.setAttributeNS(null, 'y2', 40);
secondArrow.setAttributeNS(null, 'stroke', '#ff2000');
secondArrow.setAttributeNS(null, 'stroke-linecap', 'round');
secondArrow.setAttributeNS(null, 'stroke-width', 2);
secondArrow.setAttributeNS(null, 'id', 'seconds');
// рисую стрелку
svg.appendChild(secondArrow);
}
function moveArrows() {
const now = new Date();
let seconds = now.getSeconds() * 6;
// console.log(seconds);
let minutes = now.getMinutes() * 6;
// console.log(minutes);
// задаю так часы, чтобы они не перескакивали с часа на час, а плавно шли от часа к часу
let hours = (now.getHours() + now.getMinutes() / 60 + now.getSeconds() * 3600) * 30;
// беру стрелки по Id, чтоб потом передать им анимацию
let hoursStyle = document.getElementById('hours');
let minutesStyle = document.getElementById('minutes');
let secondsStyle = document.getElementById('seconds');
// задаю анимацию
secondsStyle.setAttributeNS(null, 'transform', 'rotate(' + seconds + ' ' + widthHalf + ' ' + heightHalf + ')');
minutesStyle.setAttributeNS(null, 'transform', 'rotate(' + minutes + ' ' + widthHalf + ' ' + heightHalf + ')');
hoursStyle.setAttributeNS(null, 'transform', 'rotate(' + hours + ' ' + widthHalf + ' ' + heightHalf + ')');
let subsec = Number.isInteger(seconds/5); // Это если надо оставлять подсвеченным элемент до следующего числа.
// немного посмеяться )))
let z = document.getElementsByName('bz');
let valz = 0; // Пурум Пум Пум
let raddd = secondsStyle.getAttributeNS(null, 'transform');
let raddd1 = raddd.split('(')[1].split(' ')[0]; // Получим ротацию.
for(let iz=0;iz<z.length;iz++){
valz += 30; // Шаг 30 так как 460 же
if(raddd1 == valz){
z[iz].setAttributeNS(null, 'fill', '#f7feff');
} else {
z[iz].setAttributeNS(null, 'fill', '#74797a');
}
if (raddd1 == 0){
z[iz].setAttributeNS(null, 'fill', '#8088ff');
}
}
// создаю функцию в которой буду показывать время в виде циферок
// Блин это круто прям..... (коммент от Дениса)
function showTime(time) {
// делаю проверку для красоты, (const textHour = now.getHours() - работает одинаково)
const textHour = (now.getHours() < 10) ? ('0' + now.getHours()) : (now.getHours());
const textMinutes = (now.getMinutes() < 10) ? ('0' + now.getMinutes()) : (now.getMinutes());
const textSeconds = (now.getSeconds() < 10) ? ('0' + now.getSeconds()) : (now.getSeconds());
// беру по id мой текст и вставляю туда время
document.getElementById("text-time").textContent = textHour + ':' + textMinutes + ':' + textSeconds;
}
showTime();
DinDon();
}
function sayTime(haha) {
speechSynthesis.speak(new SpeechSynthesisUtterance(haha));
}
function DinDon() {
//let ttime = new Date().getMinutes();
ttime = new Date().getSeconds();
let submin = Number.isInteger(ttime/5);
let haha;
if (ttime/5 == 0){ // Можно было сделать функцией озвучки, но она работает по исключительно по нажатию, точнее активации. А нам надо отслеживать и триггер. Можно сделать, да и стрелку на триггер true от isInteger, но время уже... и лениво )))
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Прошла минута дорогие друзья';
} else if(ttime/5 == 1){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Пять секунд';
} else if(ttime/5 == 2){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Десять секунд';
} else if(ttime/5 == 3){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Пятнадцать секунд';
} else if(ttime/5 == 4){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Двадцать секунд';
} else if(ttime/5 == 5){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Двадцать пять секунд';
} else if(ttime/5 == 6){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Тридцать секунд';
} else if(ttime/5 == 7){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Тридать пять секунд';
} else if(ttime/5 == 8){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Сорок секунд';
} else if(ttime/5 == 9){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Сорок пять секунд';
} else if(ttime/5 == 10){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Пятьдесят секунд';
} else if(ttime/5 == 11){
document.getElementById('seconds').style.strokeWidth = '5';
haha = 'Пятьдесят пять секунд';
} else {
document.getElementById('seconds').style.strokeWidth = '2';
}
if(submin == true){
if (minsec != 1) {
sayTime(haha);
}
}
}
// Ради интереса добавить градиент
const grad = document.createElementNS(svg_xnls, 'linearGradient');
grad.setAttributeNS(null, 'id', 'grad');
const stop1 = document.createElementNS(svg_xnls, 'stop');
stop1.setAttributeNS(null, 'offset', '0%');
stop1.setAttributeNS(null, 'stop-color', 'white');
const stop2 = document.createElementNS(svg_xnls, 'stop');
stop2.setAttributeNS(null, 'offset', '100%');
stop2.setAttributeNS(null, 'stop-color', 'grey');
grad.appendChild(stop1);
grad.appendChild(stop2);
svg.appendChild(grad);
// Создаём овал
const bord = document.createElementNS(svg_xnls, 'rect');
svg.appendChild(bord);
bord.setAttributeNS(null, 'fill', 'url(#grad)');
bord.setAttributeNS(null, 'x', '80');
bord.setAttributeNS(null, 'y', '165');
bord.setAttributeNS(null, 'rx', '220');
bord.setAttributeNS(null, 'ry', '230');
bord.style.width = '142px';
bord.style.height = '50px';
bord.style.strokeWidth = '4';
// создаю элемент текста
const textTime = document.createElementNS(svg_xnls, 'text');
svg.appendChild(textTime);
// задаю стили
textTime.setAttributeNS(null, 'x', 150);
textTime.setAttributeNS(null, 'y', 200);
textTime.setAttributeNS(null, 'id', 'text-time');
textTime.setAttributeNS(null, 'fill', 'black');
textTime.style.fontSize = '2rem';
textTime.style.fontWeight = 'bold';
textTime.style.textAnchor = 'middle';
drawArrows();
moveArrows();
window.onload = function operation() {
setInterval(moveArrows, 1000);
};
<svg id="svg" width="300" height="300">
</svg>