Raj
Raj

Reputation: 1935

Change color of line with ball movement

I had to move a circle on line

ctx1.arc(x, y, 10, 0, Math.PI * 2, true);

I want to change the color of line from grey to red with the movement of ball. I was trying this

function rancolour() 
{ 
   var red = Math.floor(Math.random() *255); 
   var green = Math.floor(Math.random() *255); 
   var blue = Math.floor(Math.random() * 255); 
   ctx1.color = 'rgb('+red+','+green+','+blue+')'; 
}

Can any I help?? Both are canvas element.

Upvotes: 0

Views: 443

Answers (1)

Blindy
Blindy

Reputation: 67380

If your line starts at (x1,y1) and ends at (x2,y2), with your current position being (x,y), then you can calculate the required RGB color at every point with:

var percent=((x2-x)*(x2-x)+(y2-y)*(y2-y))/((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); 
ctx1.color='rgb('+(128*(1-percent)+255*percent)+','+(128*(1-percent))+','+(128*(1-percent))+')';

This will change the color of your ball from grey rgb(128,128,128) to red rgb(255,0,0).

Upvotes: 1

Related Questions