Path: blob/main/projects/HexGL/bkcore.coffee/ImageData.coffee
4626 views
###1Loads an image and gives access to pixel data.23@class bkcore.ImageData4@author Thibaut 'BKcore' Despoulain <http://bkcore.com>5###6class ImageData78###9Creates a new ImageData object1011@param path string The path of the image12@param callback function A callback function to be called13once th eimage is loaded14###15constructor: (path, callback)->1617@image = new Image18@pixels = null19@canvas = null20@loaded = false2122@image.onload = ()=>2324@canvas = document.createElement('canvas')25@canvas.width = @image.width26@canvas.height = @image.height2728context = @canvas.getContext('2d')29context.drawImage(@image, 0, 0)3031@pixels = context.getImageData(0,0, @canvas.width, @canvas.height)32@loaded = true3334context = null35@canvas = null36@image = null3738callback?.call(@)3940@image.crossOrigin = "anonymous"41@image.src = path4243###44Gets pixel RGBA data at given index4546@param x int In pixels47@param y int In pixels48@return Object{r,g,b,a}49###50getPixel: (x, y)->5152if !@pixels? or x < 0 or y < 0 or x >= @pixels.width or y >= @pixels.height53return {r: 0, g: 0, b:0, a:0}5455i = (y*@pixels.width + x) * 45657return {58r: @pixels.data[i]59g: @pixels.data[i+1]60b: @pixels.data[i+2]61a: @pixels.data[i+3]62}6364###65Gets pixel RGBA data at given float index using bilinear interpolation6667@param x float In subpixels68@param y float In subpixels69@return Object{r,g,b,a}70###71getPixelBilinear: (fx, fy)->7273x = Math.floor(fx)74y = Math.floor(fy)75rx = fx - x - .576ry = fy - y - .577ax = Math.abs(rx)78ay = Math.abs(ry)79dx = if rx < 0 then -1 else 180dy = if ry < 0 then -1 else 18182c = @getPixel(x, y)83cx = @getPixel(x+dx, y)84cy = @getPixel(x, y+dy)85cxy = @getPixel(x+dx, y+dy)8687cf1 = [88(1-ax) * c.r + ax * cx.r89(1-ax) * c.g + ax * cx.g90(1-ax) * c.b + ax * cx.b91(1-ax) * c.a + ax * cx.a92]9394cf2 = [95(1-ax) * cy.r + ax * cxy.r96(1-ax) * cy.g + ax * cxy.g97(1-ax) * cy.b + ax * cxy.b98(1-ax) * cy.a + ax * cxy.a99]100101return {102r: (1-ay) * cf1[0] + ay * cf2[0]103g: (1-ay) * cf1[1] + ay * cf2[1]104b: (1-ay) * cf1[2] + ay * cf2[2]105a: (1-ay) * cf1[3] + ay * cf2[3]106}107108###109Gets pixel data at given index110as 3-bytes integer (for floating-point textures erzats, from RGB values)111112@param x int In pixels113@param y int In pixels114@return int (R + G*255 + B*255*255)115###116getPixelF: (x, y)->117118c = @getPixel(x, y)119return c.r + c.g * 255 + c.b * 255 * 255120121###122Gets pixel data at given float index using bilinear interpolationas123as 3-bytes integer (for floating-point textures erzats, from RGB values)124125@param x float In subpixels126@param y float In subpixels127@return Object{r,g,b,a}128###129getPixelFBilinear: (fx, fy)->130131c = @getPixelBilinear(fx, fy)132return c.r + c.g * 255 + c.b * 255 * 255133134###135Exports136@package bkcore137###138exports = exports ? @139exports.bkcore ||= {}140exports.bkcore.ImageData = ImageData141142