UNPKG

cdf

Version:

A library for creating oldschool demo-like animations with JavaScript

53 lines (48 loc) 1.81 kB
/* drawing gradients */ (function (global) { var lib = global.cdf || {}; var grad = lib.gradient = lib.Gradient = lib.grad = function (dst, gradParams) { if(!(this instanceof lib.Gradient)){ return new grad(dst, gradParams); } if(dst && dst.ctx){ this.canvas = dst; this.params = gradParams; } else { this.canvas = new lib.Canvas(100,100); this.params = dst; } if(typeof this.params[0] === 'string') this.params = grad.interpolateColors(this.params); }; grad.interpolateColors = function(colors){ var gradParams = []; colors.forEach(function(color,index,all){ gradParams.push({color:color, offset:index/(all.length-1)}); }); return gradParams; }; grad.prototype = { getFillStyle: function(x0,y0,x1,y1){ var lingrad = this.canvas.ctx.createLinearGradient(x0, y0, x1, y1); for (var j = 0; j < this.params.length; j++) { lingrad.addColorStop(this.params[j].offset, this.params[j].color); } return lingrad; }, draw: function(x0,y0,x1,y1){ this.canvas.fill(this.getFillStyle(x0,y0,x1,y1)); return this; }, drawV: function () { return this.draw(0, 0, this.canvas.w, 0); }, drawH: function(){ return this.draw(0,0,0,this.canvas.h);}, drawAngle: function (angleInDeg, cx,cy, length) { var dst = this.canvas; cx = cx === undefined? dst.cx : cx; cy = cy === undefined? dst.cy : cy; var r = length/2 || Math.sqrt(dst.cy*dst.cy+dst.cx*dst.cx); var angle = angleInDeg * lib.utils.DEG_TO_RAD; this.draw(Math.sin(angle)*r+cx,Math.cos(angle)*r+cy,Math.sin(angle+Math.PI)*r+cx,Math.cos(angle+Math.PI)*r+cy); } }; if(typeof module!=='undefined'&& module.exports){module.exports=lib;}else{global.cdf=lib;} })(window);