2017-08-30 8 views
0

範囲入力の値に応じて動的に変化する円グラフを作成しようとしています。JavaScriptを使ってパイスライスの背景色を変更するにはどうすればよいですか?

これは私がこれまで何をやったかである:https://codepen.io/anon/pen/wqQLPy

const $slider = document.querySelector('input[type=range]'); 
 
const $line2 = document.querySelector('.line2'); 
 

 
$slider.addEventListener('input', handleChange); 
 

 
function handleChange() { 
 
    //$currrentValue.textContent = this.value; 
 
    const degrees = 90 + ((this.value/100) * 360); 
 
    $line2.style.transform = `rotate(${degrees}deg)`; 
 
}
.pie { 
 
    width: 250px; 
 
    height: 250px; 
 
    margin: 0 auto; 
 
    border-radius: 50%; 
 
    border: 3px solid white; 
 
    position: relative; 
 
    background: #ffc600; 
 
    overflow: hidden; 
 
} 
 

 
.line { 
 
    width: 50%; 
 
    height: 2px; 
 
    background: #555; 
 
    position: absolute; 
 
    top: 50%; 
 
    transform-origin: 100%; 
 
    transform: rotate(90deg); 
 
    transition: all .2s linear; 
 
} 
 

 
.line2 { 
 
    transform: rotate(180deg); 
 
    /* When input value is 25 (default) */ 
 
}
<input type="range" min="0" max="100" value="25"> 
 

 
<div class="pie"> 
 
    <div class="line line1"></div> 
 
    <div class="line line2"></div> 
 
</div>

私の質問は - スライス(2線の間の領域)に異なる背景色を設定する方法?

例:

Pie chart

答えて

1

それはこのようなもののためにSVGを使用することをお勧めします

const $slider = document.querySelector('input[type=range]'); 
 
const $currrentValue = document.querySelector('.current-value'); 
 
const $circle = document.querySelector('.circle'); 
 

 
$slider.addEventListener('input', handleChange); 
 

 
function handleChange() { 
 
    
 
    $currrentValue.textContent = this.value; 
 

 
    const degrees = this.value; 
 

 
    $circle.style = 'stroke-dasharray:'+degrees+' 150'; 
 
}
body { 
 
    text-align: center; 
 
    font-size: 2em; 
 
} 
 

 
input { 
 
    width: 300px; 
 
    max-width: 80%; 
 
} 
 

 
input:hover { 
 
    cursor: pointer; 
 
} 
 

 
.current-value { 
 
    position: relative; 
 
    top: -30px; 
 
    left: -7px; 
 
    font-weight: bold; 
 
} 
 

 
.pie{ 
 
    border-radius: 50%; 
 
} 
 

 
.pie circle { 
 
    fill: yellow; 
 
    stroke: red; 
 
    stroke-width: 30; 
 
}
<p>0 <input type="range" min="0" max="100" value="25"> 100</p> 
 
<p class="current-value">25</p> 
 

 
<div style="margin:0 auto ;width:100px; height: 100px;"> 
 
<svg class="pie" viewBox="0 0 30 30"> 
 
<circle r="15" cx="15" cy="15" transform="rotate(45,15,15)" /> 
 
    <circle class="circle" style="stroke-dasharray: 10.5 150;" r="15" cx="15" cy="15" /> 
 

 
</svg> 
 
</div>

ことを試してみてください
関連する問題