之前在想如何使用Javascript实现时钟的时候,被一个问题难到了:如何在像素级别绘制平滑的直线。
在网上查了一下,后来在图书馆里的一本关于计算机图形学的老书里发现了解决方案。针对这个问题,书上提供了三个算法,分别是简单DDA,对称DDA,Bresenham算法。
下面的是我使用简单DDA和Bresenham算法在浏览器上绘制Hello world的代码。
这里的Hello world 分别是定义了字母的一些”节点“,然后使用连线算法绘制出来的。
代码:
- //构造画布,使用DOM动态生成表格
- var _container = document.getElementById("container");
- var pixs = new Array();
- var canvasTbody = document.createElement("tbody");
- var bgColor = "black";
- var fontColor = "green";
- var pix_size = "4px";
- var pix_numbs = 81;
- var temp_tr ;
- var temp_td ;
- var temp_pixrow;
- for(var i = pix_numbs; i >= 0 ; i--){
- temp_tr = document.createElement("tr");
- temp_tr.style.height = pix_size;
- temp_pixrow = new Array();
- for(var j = 0; j <= pix_numbs ; j++){
- temp_td = document.createElement("td");
- temp_td.style.width=pix_size;
- temp_td.style.backgroundColor = bgColor;
- temp_tr.appendChild(temp_td);
- temp_pixrow[j] = temp_td;
- }
- canvasTbody.appendChild(temp_tr);
- pixs[i] = temp_pixrow;
- }
- var canvasTable = document.createElement("table");
- canvasTable.style.backgroundColor = "black";
- canvasTable.setAttribute("cellspacing","0");
- canvasTable.setAttribute("cellpadding","0");
- canvasTable.appendChild(canvasTbody);
- _container.appendChild(canvasTable);
- // 点 类,包含坐标信息,有绘制和比较操作
- function point(_x,_y){
- this.x = _x;
- this.y = _y;
- }
- function _draw(){
- if(this.x > pix_numbs || this.y > pix_numbs){
- return;
- }
- pixs[this.y][this.x].style.backgroundColor = fontColor;
- }
- point.prototype.draw = _draw;
- function _equal(_p){
- if(! _p instanceof point){
- throw new Error();
- }
- if(this.x == _p.x && this.y == _p.y){
- return true;
- }else{
- retu