UNPKG

cdf

Version:

A library for creating oldschool demo-like animations with JavaScript

109 lines (89 loc) 2.72 kB
/* pixel-perfect lines (Bresenham) and plot. Also color manipulatins. For when regular canvas features are not enough. Note these may be slow as hell. Also colors do not work yet, sorry*/ (function(global){ var lib = global.cdf || {}; var PixelData = lib.PixelData = function(w, h){ if(w instanceof lib.Canvas){ this.canvas = w; this.dataGet(); } else { this.size(w, h); } }; PixelData.prototype = { /** Get pixeldata from current canvas */ dataGet: function(){ this.w = this.width = this.canvas.w; this.h = this.height = this.canvas.h; this.iData = this.canvas.ctx.getImageData(0,0,this.w,this.h); this.data = this.iData.data; return this; }, /** Set pixel data to current canvas */ dataSet: function () { this.canvas.clear(); this.canvas.ctx.putImageData(this.iData, 0,0); return this; }, clear: function(){ this.canvas.clear(); return this.dataGet(); }, fill: function(color){ this.canvas.clear().fill(color); this.dataGet(); return this; }, size: function(w,h){ this.canvas = this.canvas || new lib.Canvas(w.h); this.canvas.setSize(w,h); return this.dataGet(); }, getOffset:function(x, y){ return (Math.floor(y)*this.w + Math.floor(x))*4; }, draw: function(dst){ this.dataSet(); if(dst && this.canvas !== dst) this.canvas.draw.apply(this.canvas, arguments); return this; }, get: function(x,y){ var offset = this.getOffset(x,y); return this.data.slice(offset, offset+4); }, plot: function(x,y, r,g,b,a){ if(a===undefined) a = 255; r=r||0; g=g||0; b=b||0; if(!lib.utils.between(x,0,this.w) || !lib.utils.between(y,0,this.h))return; var offset = this.getOffset(x,y); this.data[offset] = r; this.data[offset+1] = g; this.data[offset+2] = b; this.data[offset+3] = a; return this; }, line: function(x0,y0,x1,y1,r,g,b,a){ x0 = Math.floor(x0); x1 = Math.floor(x1); y0 = Math.floor(y0); y1 = Math.floor(y1); var dx = Math.abs(x1 - x0), dy = Math.abs(y1 - y0), sx = (x0 < x1) ? 1 : -1, sy = (y0 < y1) ? 1 : -1, err = dx - dy; while (1) { this.plot(x0, y0, r, g, b, a); if ((x0 === x1) && (y0 === y1)) break; var e2 = 2 * err; if (e2 > -dy) { err -= dy; x0 += sx; } if (e2 < dx) { err += dx; y0 += sy; } } return this; } }; if(typeof module!=='undefined'&& module.exports){module.exports=lib;}else{global.cdf=lib;} })(window);