您的位置:首页 > Web前端 > HTML5

H5 canvas 实现排序算法过程动画

2017-12-26 18:52 525 查看

H5 canvas 实现排序算法过程动画

实现思路

通过柱状图方式,绘制数组数据,每一次交换数组数据时重绘



(用的录屏软件,貌似录得有点重影)

1、定义一个canvas

body{
margin: 0;
padding: 0;
background: #F6F6F6;
}

.div1 {
margin: 50px auto;
width: 500px;
}

#cvs {
background: #FFF;
box-shadow: 0px 0px 1px 1px #555555;
margin: 10px;
}

<div class="div1">
<canvas id="cvs" width="500" height="500"></canvas>
<button onclick="start()">开始</button>
</div>


2、具体实现代码

var cvs = document.getElementById('cvs');
var ctx = cvs.getContext('2d');
var lists = [32, 31, 29, 26, 20, 24, 35, 6, 25, 39, 13,
33, 8, 38, 10, 18, 5, 3, 27, 21, 17, 34, 28, 14,
12, 23, 7, 22, 16, 19, 37, 9, 2, 30, 11, 36, 4,
15, 40, 1];
var index = 0;      //延时函数计数
draw(lists);


绘柱状图 函数

//清空画布
function clearCanvas(){
ctx.clearRect(0, 0, cvs.width, cvs.height);
}

//绘柱状图,高亮交换位
function draw(arr, first, second){
clearCanvas();
for(var i in arr){
var x = 10 + 12 * i;
var y = arr[i] * 10;
ctx.beginPath();
if(i == first)
ctx.fillStyle = 'yellow';
else if(i == second)
ctx.fillStyle = 'yellow';
else ctx.fillStyle = 'orange';
ctx.fillRect( x, 480 - y, 10, y );
ctx.closePath();
}
}


使用swap函数交换数组数据时延时绘图

//完整复制数组
function cpy(arr){
var item = [];
for(var i in arr){
item[i] = arr[i];
}
return item;
}

//交换数据时延时画图,高亮交换位
function swap(items, firstIndex, secondIndex){
//交换数据
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
//延时画图
var ls = cpy(items);
setTimeout(function(){
draw(ls, firstIndex, secondIndex);
}, index * 100);
index ++;
}


快排算法,直接借鉴的别人的代码,如果是其他排序算法,只要把交换数据部分改成swap函数,同样可以绘制出动画

https://www.cnblogs.com/aaronjs/p/3539538.html

function partition(items, left, right) {
var pivot = items[Math.floor((right + left) / 2)],
i = left,
j = right;
while (i <= j) {
while (items[i] < pivot) {
i++;
}
while (items[j] > pivot) {
j--;
}
if (i <= j) {
swap(items, i, j);
i++;
j--;
}
}
return i;
}

function quickSort(items, left, right) {
var index;
if (items.length > 1) {
index = partition(items, left, right);
if (left < index - 1) {
quickSort(items, left, index - 1);
}
if (index < right) {
quickSort(items, index, right);
}

}
return items;
}


开始按钮绑定事件

function start(){
draw(lists);            //开始绘图
var arr = cpy(lists);   //复制数组,下次可以重新开始动画
index = 0;              //初始化延时计数
quickSort( arr, 0, arr.length - 1 );    //执行快排
setTimeout(function(){  //结束绘图
draw(arr);
}, index * 100);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息