利用Konva封裝簡易的進度條

利用Konva庫封裝了一個簡單的進度條函數tjProgressBar,效果如下:

主要是引入Konva.js與tjProgressBar.js後,在頁面中直接初始化一個tjProgressBar對象即可創建一個進度條。

new tjProgressBar({
	x:100, 
	y:100, 
	w:600, //進度條的寬度
	h:30 //進度條的高度
});

具體代碼如下:

html:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>進度條</title>
	<style>
		*{
			padding: 0;
			margin:0;
		}
	</style>
	<script src="js/konva.js"></script>
	<script src="tjJs/tjProgressBar.js"></script>
</head>
<body>
	<div id="container">
		
	</div>
	
	<script>
		var stage = new Konva.Stage({
			container: "container",
			width:window.innerWidth,
			height:window.innerHeight
		});
		var layer = new Konva.Layer();
		stage.add(layer);

		var pBar = new tjProgressBar({
			x:100,
			y:100,
			w:600,
			h:30
		});
		pBar.addGroupOrLayer(layer);
		pBar.changeWidth(.8);
		layer.draw();

	</script>
</body>
</html>

tjProgressBar.js

function tjProgressBar(option){
	this._init(option);
}
tjProgressBar.prototype = {
	_init:function(option){
		this.x = option.x || 0;
		this.y = option.y || 0;
		this.w = option.w || 0;
		this.h = option.h || 0;

		this.fillStyle = option.fillStyle || "#07B0FA"; //進度條顏色
		this.strokeStyle = option.strokeStyle || "#E5E6EA"; //進度條邊框顏色

		this.group = new Konva.Group({
			x:0,
			y:0
		});
		var strokeW = 10; //邊框的寬度
		var outerRect = new Konva.Rect({
			x:this.x,
			y:this.y,
			width:this.w,
			height:this.h,
			stroke:this.strokeStyle,
			fill:"#B3B2B0",
			strokeWidth:strokeW,
			cornerRadius:1/2*this.h
		});
		this.group.add(outerRect);

		var innerRect = new Konva.Rect({
			x:this.x+strokeW/2,
			y:this.y+strokeW/2,
			width:0,
			height:this.h-strokeW,
			fill:this.fillStyle,
			cornerRadius:1/2*this.h,
			id:"innerRect"
		});
		this.group.add(innerRect);
	},
	//動畫:改變innerRect中Width的值
	changeWidth:function(value){
		if(value>1){
			value = value/100;
		}
		var width = value*this.w;
		var innerRect = this.group.findOne("#innerRect");
		innerRect.to({
			width:width,
			duration:.3,
			easing:Konva.Easings.EasIn
		});
	},
	
	addGroupOrLayer:function(arg){
		arg.add(this.group);
	}
}

Konva可以去其官網下載:

https://konvajs.org/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章