0
我正在嘗試創建具有獨特形狀的進度條。我知道如何填充形狀,但我不知道如何填充百分比。作爲進度條在畫布中填充描邊
我嘗試使用fillRect
,但它填補了畫布的形狀,沒有在最後的圓圈。
這就是我想要實現:
,這是我的例子:https://jsfiddle.net/
我正在嘗試創建具有獨特形狀的進度條。我知道如何填充形狀,但我不知道如何填充百分比。作爲進度條在畫布中填充描邊
我嘗試使用fillRect
,但它填補了畫布的形狀,沒有在最後的圓圈。
這就是我想要實現:
,這是我的例子:https://jsfiddle.net/
最簡單的方法是,以填補一個矩形背景所選區域的寬度和形狀最大高度的高度,然後使用合成操作僅保留形狀重疊的部分,最後繪製筆畫。
slider.oninput = drawGauge;
function drawGauge(evt){
// first convert the value to our pixel system
var value = (width/100) * evt.target.value;
// clear the previous frame
ctx.clearRect(0,0,canvas.width, canvas.height);
// draw the filled rect the width of our value
ctx.fillRect(marginLeft, marginTop, value, circleRad*2);
// change the gCO so we keep only the pixels where our shape and the filled rect overlap
ctx.globalCompositeOperation = 'destination-in';
drawShape();
ctx.fill(); // this will make the compositing
// reset the gCO so we can draw the stroke
ctx.globalCompositeOperation = 'source-over';
ctx.stroke();
}
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'lightblue';
ctx.strokeStyle = 'lightgray';
// the positions of our shapes
var marginLeft = 5,
marginTop = 5,
width = 280,
circleRad = 30,
circleCenter = width - circleRad,
rectHeight = 30,
rectTop = marginTop + (circleRad - rectHeight/2),
rectWidth = width - circleRad * 1.82;
// you may have a better version of it ;-)
function drawShape(){
ctx.beginPath();
ctx.moveTo(marginLeft, rectTop);
ctx.lineTo(rectWidth, rectTop);
ctx.arc(circleCenter+1, rectTop + rectHeight /2, circleRad, -Math.PI*.8, Math.PI*.8);
ctx.lineTo(marginLeft, rectTop+ rectHeight);
ctx.closePath();
}
drawGauge({target:{value:50}});
<input type="range" id="slider" from="0" to="100" value="50"/><br>
<canvas id="canvas"></canvas>