이 글에서는 캔버스 링 카운트다운 컴포넌트의 샘플 코드를 소개하고, 자세한 내용은 다음과 같습니다.
효과는 그림 1과 같습니다.
캔버스 링 카운트다운 구성요소캔버스 링 카운트다운은 캔버스를 기반으로 구현된 카운트다운으로 모바일 기기에서 사용을 권장합니다.
캔버스 링 카운트다운 다운로드 주소
1. 사용방법1. HTML 코드
ID 속성은 임의로 이름을 지정할 수 있습니다.
<캔버스 id=캔버스></canvas>
2. process.js 파일 소개
페이지 참조
<script src=js/process.js></script>
3. 초기화 매개변수
그냥 인스턴스화하세요
<script> window.onload = function () { let ctd = new Countdown() };</script> 2. 설정 매개변수 설명다음 매개변수는 필수가 아니며 특정 요구에 따라 구성할 수 있습니다.
window.onload = function () { let ctd = new Countdown(); ctd.init({ id: canvas, // ID, canvas는 ID 속성이 있어야 합니다. size: 130, // 원을 그리는 최대 크기, width = High borderWidth: 4, // 테두리 너비 borderColor: #fff, // 테두리 색상 externalColor: #fff, // 가장 바깥쪽 하단 원 색상 ScheduleColor: #fff, // 진행률 표시줄 애니메이션 색상 글꼴 색상: #fff, // 글꼴 색상 ringColor: #ffc720, // 진행률 표시줄 링 색상 innerColor: #4e84e5, // 가장 안쪽 원 배경 색상 글꼴 크기: 50, 시간: 5 }); 3. 샘플 코드HTML
<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <title>제목</title> <style> body { background: #c2c1ce } .container { 위치: 절대 왼쪽: 50%; 상단: 50%; 변환:(-50%, -50%); 너비: 130px; center; } </style></head><body><div class=container> <canvas class=canvas id=canvas></canvas></div><script src=js/process.js></script ><script> window.onload = function () { let ctd = new ctd.init() };</script></body></html>JS
/** * Tan Xi가 2018년 3월 15일에 생성했습니다. */function Countdown() { // 기본 매개변수 설정 this.settings = { id: canvas, // ID, canvas는 ID 속성 크기: 130을 가져야 합니다. // 원을 그리는 최대 크기, width = height borderWidth: 4, // 테두리 너비 borderColor: #fff, // 테두리 색상 externalColor: #fff, // 가장 바깥쪽 하단 원 색상 ScheduleColor: #fff, // 진행률 표시줄 애니메이션 색상 FontColor: #fff, // 글꼴 색상 ringColor: #ffc720, // 진행률 표시줄 링 색상 innerColor: #4e84e5, // 가장 안쪽 원 배경색 FontSize : 50, 시간: 5 }}Countdown.prototype.init = 함수(선택 사항) { this.obj = document.getElementById(this.settings.id); this.obj.width = this.settings.size; this.obj.height = this.settings.size; this.ctx = this.obj.getContext(2d); this.settings, opt); this.countdown();};//배경색 그리기 Countdown.prototype.drawBackground = function () { this.drawCircle(0, 360, 0, this.settings.outerColor);};// 진행률 표시줄 애니메이션 배경 그리기 Countdown.prototype.drawProcess = function () { this.drawCircle(0, 360, 4, this.settings.ringColor);};/ / 그리기 카운트다운 Countdown.prototype.drawInner = function () { this.drawCircle(0, 360, 23, this.settings.innerColor); this.StrokeBorder(this.settings.borderWidth);};// 진행률 표시줄 애니메이션 그리기 Countdown.prototype.drawAnimate = function () { // 회전 각도 let deg = Math.PI / 180; v = 일정 * 360, startAng = -90, endAng = -90 + v this.ctx.beginPath(); this.ctx.moveTo(this.settings.size / 2, this.settings.size / 2) this.ctx.arc(this.settings.size / 2, this.settings.size / 2, this.settings.size / 2 -3, startAng * deg, endAng * deg, false) this.ctx.fillStyle = this.settings.scheduleColor(); this.ctx.closePath();};// 테두리 그리기 Countdown.prototype.StrokeBorder = function (borderWidth) { this.ctx.lineWidth = borderWidth; this.ctx.StrokeStyle = this.settings.borderColor; 스트로크 ();};// 텍스트 그리기 Countdown.prototype.스트로크텍스트 = 함수 (텍스트) { this.ctx.textAlign = center; this.ctx.textBaseline = 중간; this.ctx.font = this.settings.fontSize+px+ microsoft yahei; this.ctx.fillStyle = this.ctx.fillText(text, this.settings.size / 2, this.settings.size / 2);};// 원 그리기 Countdown.prototype.drawCircle = function (startAng, endAng, border, fillColor) { let deg = Math.PI / 180; this.ctx.beginPath(); this.ctx.arc(this.settings.size / 2, this.settings.size / 2, this.settings.size / 2 -border, startAng * deg, endAng * deg, false) this.ctx.fillStyle = fillColor; this.ctx.closePath();};//진행률 표시줄 애니메이션 Countdown.prototype.countdown = function () { let oldTime = +new Date(); 타이머 = setInterval(() => { let allMs = this.settings. time * 1000,// 예를 들어 30*1000=30 000ms currentTime = +new Date() // 단계 크기 = (현재 시간 - 지난 시간) / 총 초 수 Schedule = (currentTime - oldTime) / allMs = this.drawAll(schedule); if (currentTime - oldTime >= allMs) 다시 그리기 this.drawBackground(); this.drawAnimate(); clearInterval(timer); } }, 100);};// 모두 그리기 Countdown.prototype.drawAll = function (schedule) { 일정 = 일정 >= 1 ? 1 : 일정; (1 - 일정)) + 1; // 캔버스 지우기 this.ctx.clearRect(0, 0, this.settings.size, this.settings.size); this.drawBackground(); this.drawProcess(); this.drawInner(); this.스트로크텍스트(text);};//객체 복사 함수 확장(obj1,obj2){ for(let attr obj2){ obj1[attr] = obj2[attr] }} 4. 추가 캔버스 준비작업사실 캔버스는 다른 HTML 태그와 마찬가지로 H5 태그에 지나지 않습니다.
<캔버스 id=캔버스></canvas>
처음에 캔버스의 너비와 높이를 설정하는 것이 가장 좋습니다(너비와 높이를 설정하지 않으면 브라우저는 기본적으로 캔버스 크기를 너비 300픽셀, 높이 100픽셀로 설정합니다). CSS를 사용하여 설정하려면(확장을 가져옵니다) 캔버스 태그 내부에 직접 작성하는 것이 좋습니다.
<canvas id=canvas width=130 height=130></canvas>
Canvas 자체에는 그리기 기능이 없으며, 모든 그리기 작업은 js를 통해 구현됩니다. 일반적으로 우리는 작업할 캔버스를 가져오기 위해 js에서 getElementById를 사용합니다(즉, 캔버스에 ID를 설정해야 함을 의미합니다).
var c = document.getElementById(canvas);var ctx = c.getContext(2d);
1. 브러시를 준비한 후 링은 실제로 반경이 다른 동심원입니다. 중심 좌표는 (크기/2, 크기/2)입니다. 먼저 반경이 크기/2인 가장 큰 흰색 배경 하단 원을 그립니다. .
let deg = Math.PI / 180; // BeginPath()는 경로 그리기 효과를 분리하고 이전 효과가 오염되는 것을 방지할 수 있습니다. ctx.beginPath();// tcx.arc(원 중심 각도, 360 * 각도, false);ctx.fillStyle = #fff;ctx.fill();ctx.closePath();
2. 두 번째 노란색 하단 원 그리기를 시작합니다. 원의 중심도 (크기/2, 크기/2)이지만 반경은 흰색 하단 원보다 4px 작으므로 노란색 하단 원의 반경은 (크기 /2-4)
let deg = Math.PI / 180; // BeginPath()는 경로 그리기 효과를 분리하고 이전 효과가 오염되는 것을 방지할 수 있습니다. ctx.beginPath();//tcx.arc(원 중심 0* 도, 360 * 도, false);ctx.fillStyle = #fff;ctx.fill();ctx.closePath();
3. 원의 중심이 (size/2,size/2)이고 반경이 (size-23)인 파란색 내부 원 그리기를 시작한 다음 4px 흰색 테두리를 추가합니다.
let deg = Math.PI / 180; // BeginPath()는 경로 그리기 효과를 분리하고 이전 효과가 오염되는 것을 방지할 수 있습니다. ctx.beginPath();// tcx.arc(원 중심 0* 도, 360 * 도, false);ctx.fillStyle = #fff;ctx.fill();ctx.closePath();// 흰색 테두리 ctx.lineWidth = 4;ctx.StrokeStyle = #fff;ctx.Stroke();
4. 텍스트를 그리고 세로 중앙에 배치
ctx.textAlign = center;ctx.textBaseline = middle;ctx.fillStyle = #fff;// ctx.fillText (텍스트, 캔버스를 기준으로 한 X 좌표, 캔버스를 기준으로 한 Y 좌표) ctx.fillText(30, 크기 / 2 , 크기 / 2);
5. 애니메이션을 만드는 방법은 무엇입니까? 사실 흰색 원을 그리는 과정이기도 합니다. 노란색 진행 표시줄을 천천히 덮는 과정입니다. 이때 흰색 원이 먼저 그려지면 흰색 애니메이션 원이 덮이게 됩니다. , 마지막 파란색 원이 그려집니다.
let deg = Math.PI / 180;ctx.beginPath();// tcx.arc(원 중심 X, 원 중심 Y, 반경, 시작 각도, 끝 각도, 시계 방향 및 시계 반대 방향);ctx.arc(크기 / 2, 크기 / 2, 크기 / 2-4, 0* 도, 360 * 도, false);ctx.fillStyle = #fff;ctx.fill();ctx.closePath();
6. 상대적으로 간단한 페인팅 프로세스가 완료되었습니다. 다음으로 애니메이션을 숫자와 연결해야 합니다. 현재 가장 늦은 시간을 사용하고 총 시간을 나누어 이 백분율을 결정할 수 있습니다. 숫자와 흰색 애니메이션 원이 그려지는 각도가 변경됩니다.
Countdown.prototype.countdown = function () { let oldTime = +new Date(); // 지난 시간: 1522136419291 타이머 = setInterval(() => { let currentTime = +new Date(); // 현재 시간: 1522136419393 let allMs = this.settings.time * 1000;// 총 시간(초): 예: 30*1000=30 000ms 일정 = (currentTime - oldTime) / allMs;// 그리기 비율: (1522136419393-1522136419291)/30000=0.0204 this.schedule = Schedule; this.drawAll(schedule); if (currentTime - oldTime >= allMs) { // 다시 그리기 this.drawProcess(); this.drawInner();clearInterval(timer); .prototype.drawAll = 함수(일정) { 일정 = 일정 >= 1 ? 1 : 일정; 텍스트 = 구문 분석(this.settings.time * (1) - 일정)) + 1; // 캔버스 지우기 this.ctx.clearRect(0, 0, this.settings.size, this.settings.size) this.drawProcess(); ( ); this.drawInner(); this.strokText(text);};// 진행률 표시줄 애니메이션 그리기 Countdown.prototype.drawAnimate = function () { // 회전 각도 let deg = Math.PI / 180; v = 일정 * 360, startAng = -90,//시작 각도 endAng = -90 + v;//끝 각도 this.ctx.beginPath() this.ctx.moveTo(this.settings) .size / 2, this.settings.size / 2); this.ctx.arc(this.settings.size / 2, this.settings.size / 2, this.settings.size / 2 - 3, startAng * deg, endAng * deg, false) this.ctx.fillStyle = this.ctx.fill(); ;프로세스 지향 버전
/** * 진행률 표시줄 애니메이션*/ countdown: function () { this.getSystemInfo().then(v => { // 적응형 let width = v.windowWidth, size = width >= 414 ? 66 : 400 / 414 * 66; size = parsInt(size); size = size % 2 ? size + 1 : size; let maxtime = +new 날짜, 임시 = setInterval(() => { let time = maxtime * 1000, currentTime = +new 날짜, 일정 = (currentTime - sTime) / time; this.drew(schedule, maxtime, size); if (currentTime - sTime >= time ) { // 텍스트 그리기 this.setData({ Schedule: 0 });clearInterval(temp) }, }); draw*/ draw: function (schedule, val, size) { size = size || 66; const _ts = this; 일정 = 일정 >= 1 ? 1 : 일정; parsInt(val - val * 일정) = 크기 / 2, deg = Math.PI / 180; _ts.setData({ 너비: 크기, 높이: 크기, 일정: 텍스트 + 1 }); 캔버스 지우기 ctx.clearRect(0, 0, size, size); // 흰색 배경 그리기 ctx.beginPath(); ctx.arc(r, r, r, 0 * deg, 360 * deg); = 'rgba(255,255,255,1)'; ctx.closePath(); 주황색 그리기 ctx.beginPath(); ctx.arc(r, r, r - 2, 0 * deg, 360 * deg); ctx.fillStyle = 'rgba(248,200,80,1)'; ctx.fill(); // 흰색 진행 표시줄을 그립니다. let v = Schedule * ctx.beginPath(); ctx.moveTo(r, r); ctx.arc(r, r, r, -90 * deg, (-90 + v) * deg); ctx.fillStyle = 'rgba(255,255,255,1)'; (); ctx.fill(); // 중앙 파란색 하단 ctx.beginPath(); r - 12, 0 * deg, 360 * deg); ctx.fillStyle = 'rgba(90,140,220,1)' ctx.closePath(); // 텍스트를 그립니다. 통합 도면 ctx.draw() },위의 내용은 이 기사의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다. 또한 모든 분들이 VeVb Wulin Network를 지지해 주시길 바랍니다.