Jump to content

hexColor: Plugin for tweening hex color values


eozan
 Share

Recommended Posts

Hi,

 

I needed to tween color of some text, but it's not possible as it's in '#ff9900' format. So I wrote a plugin to make it possible.

 

Here is the code: (Note: You need lodash or underscore library, or just change _ instances to handle it however you like, it's not doing anything difficult)

//var _ = require('lodash');var HexColor = function(game, parent) {    Phaser.Plugin.call(this, game, parent);    this.items = [];};HexColor.prototype = Object.create(Phaser.Plugin.prototype);HexColor.prototype.constructor = Phaser.Plugin.HexColor;HexColor.prototype.add = function(item, source, destination) {    this.remove(item, source, destination);    item[source] = this._color(item[destination]);    this.items.push({        item: item,        source: source,        destination: destination    });};HexColor.prototype.remove = function(item, source, destination) {    var criteria = {};    criteria.item = item;    if (source) {        criteria.source = source;    }    if (destination) {        criteria.destination = destination;    }    _.remove(this.items, criteria);};HexColor.prototype._color = function(h) {    //http://stackoverflow.com/questions/11068240/    var m = h.match(/^#([0-9a-f]{6})$/i)[1];    if (m) {        return {            r: Math.floor(parseInt(m.substr(0, 2), 16)),            g: Math.floor(parseInt(m.substr(2, 2), 16)),            b: Math.floor(parseInt(m.substr(4, 2), 16))        };    }};HexColor.prototype._hex = function(c) {    //http://stackoverflow.com/questions/5623838/    return '#' + ((1 << 24) + (c.r << 16) + (c.g << 8) + c..toString(16).slice(1);};HexColor.prototype.update = function() {    var self = this;    _.each(this.items, function(i, index){        var rgb = i.item[i.source];        rgb.r = Math.floor(rgb.r);        rgb.g = Math.floor(rgb.g);        rgb.b = Math.floor(rgb.;        i.item[i.destination] = self._hex(rgb);    });};

Usage:

var hexColor = game.plugins.add(Phaser.Plugin.HexColor);var text = this.add.text(50, 50, 'test');text.fill = '#ffffff';hexColor.add(text, 'rgb', 'fill'); // text.rgb will hold tweenable rgb values and constantly update text.fill with hex equalthis.game.add.tween(text.rgb).to({r: 0, g: 0, b: 0}, 1000, Phaser.Easing.Linear.In).to({r: 255, g: 255, b: 255}, 1000, Phaser.Easing.Linear.In).loop().start();// or, alternatively:this.game.add.tween(text.rgb).to(hexColor._color('#000000'), 1000, Phaser.Easing.Linear.In).to(hexColor._color('#ffffff'), 1000, Phaser.Easing.Linear.In).loop().start();hexColor.remove(text, 'rgb', 'fill'); // no more updates for text.rgb -> text.fillhexColor.remove(text); // no updates for any text.source -> text.destination pairs

Enjoy!

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...