Jump to content

How do I change/update the color of a rectangle


FlakeGunner
 Share

Recommended Posts

I'm trying to update a rectangle drawn using drawRect by changing the value of fillColor but I can't get it to work.  Here's my code:

 

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create});

function preload() {
	
}

function create() {

	this.rect = game.add.graphics(0, 0);

	game.stage.backgroundColor = '#FBFAFA';


	this.rect.beginFill(0xf44253);
	this.rect.lineStyle(15, 0xf44253, 1);

	this.rect.drawRect(350, 250, 100, 100);

	game.input.onDown.addOnce(changeColour, this);

	window.graphics = this.rect;

}

function changeColour()
{
	debugger;
	var newColour = Phaser.Color.hexToRGB('#42f445');
    this.rect.graphicsData[0].fillColor = newColour; 
    console.log("clicked");

}

On mouseclick changeColour is getting called and I can see in the debugger this.rect.graphicsData[0].fillcolor is being changed from 16007763 to 21165125 which are the correct color values in 0xAARRGGBB format. 

Do I need to call a function to get this.rect to redraw the rect primitive? 

I know I can call this.rect.clear() and call beginFill/drawRect again with the new color but I'd seen other examples on this forum of people just setting fillColor directly.

Link to comment
Share on other sites

Kept banging away at trying to get fillColor to work but no luck.  After reading through some more forum posts seems tinting a sprite is another way to achieve the effect I want.  Here's the code I used if anyone is interested in the future.

rounded_square.png and rounded_square_small.png are just white squares to take the tint.

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update});

function preload() {
	game.load.image('square', 'assets/rounded_square.png');
	game.load.image('square_small', 'assets/rounded_square_small.png');
}

function create() {
	bigSquare = game.add.sprite(375, 275, 'square');
	bigSquare.tint = 0x4286f4;	

	smallSquare = game.add.sprite(375, 375, 'square_small');
	smallSquare.tint = 0xa522f7;

	game.input.onDown.addOnce(changeColour, this);
}

function changeColour() {
	bigSquare.tint = 0x21f7ef;
	smallSquare.tint = 0xdaf721;
}

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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