Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9004

canvasを使わずdiv要素で強引に線を引く

$
0
0
任意の始点座標・終点座標を結ぶ直線を引きます。 JavaScriptでのグラフィカルな表現はcanvasを使うのが普通ですが、あえてdiv要素を使ってみました。 直線1本ごとに1つの要素を使いますので、大量に線を引く用途には向かないと思います。 動作デモ <!DOCTYPE html> <html lang='ja'> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width,initial-scale=1'> <title>line sample</title> <body> <script> const line = (sx, sy, ex, ey, borderStyle) => { const body = document.querySelector('body'); body.insertAdjacentHTML('beforeend', '<div></div>'); const e = body.lastChild, s = e.style; s.borderTop = borderStyle; const width = Math.sqrt(Math.pow(sx - ex, 2) + Math.pow(sy - ey, 2)), deg = Math.atan2(ey - sy, ex - sx) * 180 / Math.PI, btw = parseFloat(getComputedStyle(e).borderTopWidth); s.position = 'absolute'; s.height = 0; s.width = `${width}px`; s.left = `${sx - width / 2}px`; s.top = `${sy - btw / 2}px`; s.transform = `rotate(${deg}deg) translateX(${width / 2}px)`; }; // example window.addEventListener('DOMContentLoaded', () => { { let sx, sy; window.addEventListener('click', e => { const ex = e.pageX; const ey = e.pageY; if(sx !== undefined && sy !== undefined) { line(sx, sy, ex, ey, '1px brown solid'); } [sx, sy] = [ex, ey]; }); } { let sx, sy, count = 0, h = 0; const a = 5 + Math.random() * 15; const b = 5 + Math.random() * 15; const r1 = 20 + Math.random() * 160; const r2 = 180 - r1; function loop() { const ex = 190 + (Math.cos(count / a) * r1 - Math.sin(count / b) * r2); const ey = 200 + (Math.sin(count / a) * r1 - Math.cos(count / b) * r2); if(sx !== undefined && sy !== undefined) { line(sx, sy, ex, ey, `1px hsl(${h}, 100%, 50%) solid`); } h++; h %= 360; [sx, sy] = [ex, ey]; if(++count < 1000) requestAnimationFrame(loop); } loop(); } }); </script> </body> </html>

Viewing all articles
Browse latest Browse all 9004

Trending Articles