开发者

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('+r开发者_JS百科ed+','+green+','+blue+')'; 
}

Can any I help?? Both are canvas element.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜