如何改变这个(纯粹的js)的颜色?

时间:2016-03-19 05:44:29

标签: javascript

我正在尝试将此mousefollow实现到我的网站中:

http://codepen.io/hakimel/pen/KanIi

但我想要自己的自定义颜色而不是默认显示的颜色。我更改了fillcolor值,并且能够更改为一种特定的颜色,但我想要4种不同的颜色。所以我尝试在 fillColor:旁边为此功能添加特定颜色,但没有这样的运气。我还创建了一个fillcolor2:属性,如:

    for (var i = 0; i < QUANTITY; i++) {
    var particle = {
        size: 1,
        position: { x: mouseX, y: mouseY },
        offset: { x: 0, y: 0 },
        shift: { x: mouseX, y: mouseY },
        speed: 0.01+Math.random()*0.04,
        targetSize: 1,
        fillColor: '#bf3e27',
        fillColor2: '#1c305c',
        orbit: RADIUS*.1 + (RADIUS * .5 * Math.random())
    };

并补充说:

    context.fillStyle = particle.fillColor2;
    context.strokeStyle = particle.fillColor2;

但这也不起作用。我还尝试复制并粘贴相同的js代码,看看它是否可行,只是更改了fillcolor,但它只会显示最后一个粘贴。

有谁能告诉我如何以最简单的方式获得4种不同的颜色,我觉得我非常过于复杂,但很明显是初学者而且对此感到非常沮丧?

最后,我希望4种不同颜色可以跨越不同的半径,并且我使用不同的RADIUS变量进行了混乱,但是如果只有一种颜色,几乎不可能弄清楚如何实现我想要的颜色。因此每种颜色会有4种,我将QUANTITY更改为:

var QUANTITY = 16;

我需要前4个半径为10的半径,所以对于我设置的第一个颜色:

var RADIUS = 10;

理想情况下,我需要前4个颜色(#AAAAAA)半径为10,但需要第二个4为半径10和30之间的颜色(#BBBBBBB),第三个颜色(#CCCCCC)是在半径30-50之间,最后的第四种颜色(#DDDDDD)在50到70之间。

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

定义数组中粒子的设置

// I've changed the color for better visibility
var ParticleSettings = [
  {color: "#f00", radiusMin: 10, radiusMax: 10},
  {color: "#0f0", radiusMin: 10, radiusMax: 30},
  {color: "#00f", radiusMin: 30, radiusMax: 50}
];

要获得粒子的正确设置(在本例中为其索引),请使用此函数

function getParticleSettings(particleIndex) {
  var settingsIndex = Math.floor(particleIndex / 4) % ParticleSettings.length,
      settings = ParticleSettings[settingsIndex];

  return {
    color: settings.color,
    radius: getRandom(settings.radiusMin, settings.radiusMax)
  };
}

getRandom只是一个小辅助函数,可以在两个边界之间得到一个随机数

function getRandom(min, max) {
  return Math.floor((Math.random() * (max - min)) + min)
}

createParticle中,我们必须更改for循环以获取当前粒子的设置

for (var i = 0; i < QUANTITY; i++) {
    // get the settings for the current particle
    var particleSettings = getParticleSettings(i);

    var particle = {
        size: 1,
        position: { x: mouseX, y: mouseY },
        offset: { x: 0, y: 0 },
        shift: { x: mouseX, y: mouseY },
        speed: 0.01+Math.random()*0.04,
        targetSize: 1,
        fillColor: particleSettings.color,    // <--
        orbit: particleSettings.radius        // <--
    };

    particles.push( particle );
}

This将是上述更改的结果。

答案 1 :(得分:3)

您可以将QUANTITYCOLORRADIUS的定义替换为这些数组的定义,同时定义RADIUS的范围:

var GROUPS = [
    {
        QUANTITY: 4,
        RADIUS: [ 5, 10],
        COLOR: 0x888888
    },
    {
        QUANTITY: 4,
        RADIUS: [10, 30],
        COLOR: 0xAA80AA
    },
    {
        QUANTITY: 4,
        RADIUS: [30, 50],
        COLOR: 0xA0A0CC
    },
    {
        QUANTITY: 4,
        RADIUS: [50, 70],
        COLOR: 0xFFE0E0
    }
];

然后在createParticles函数内部迭代GROUPS

for (var g = 0; g < GROUPS.length; g++) {
    var attribs = GROUPS[g];
    for (var i = 0; i < attribs.QUANTITY; i++) {
        var particle = {
            size: 1,
            position: { x: mouseX, y: mouseY },
            offset: { x: 0, y: 0 },
            shift: { x: mouseX, y: mouseY },
            speed: 0.01+Math.random()*0.04,
            targetSize: 1,
            fillColor: '#' + attribs.COLOR.toString(16),
            orbit: attribs.RADIUS[0] + 
                   (attribs.RADIUS[1]-attribs.RADIUS[0]) * Math.random()
        };

        particles.push( particle );
    }
}

这是一个片段:

&#13;
&#13;
// One of my first <canvas> experiments, woop! :D 

var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;

var GROUPS = [
    {
        QUANTITY: 4,
        RADIUS: [ 5, 10],
        COLOR: 0x888888
    },
    {
        QUANTITY: 4,
        RADIUS: [10, 30],
        COLOR: 0xAA80AA
    },
    {
        QUANTITY: 4,
        RADIUS: [30, 50],
        COLOR: 0xA0A0CC
    },
    {
        QUANTITY: 4,
        RADIUS: [50, 70],
        COLOR: 0xFFE0E0
    }
];

var RADIUS_SCALE = 1;
var RADIUS_SCALE_MIN = 1;
var RADIUS_SCALE_MAX = 1.5;

var canvas;
var context;
var particles;

var mouseX = SCREEN_WIDTH * 0.5;
var mouseY = SCREEN_HEIGHT * 0.5;
var mouseIsDown = false;

function init() {

  canvas = document.getElementById( 'world' );
  
  if (canvas && canvas.getContext) {
		context = canvas.getContext('2d');
		
		// Register event listeners
		window.addEventListener('mousemove', documentMouseMoveHandler, false);
		window.addEventListener('mousedown', documentMouseDownHandler, false);
		window.addEventListener('mouseup', documentMouseUpHandler, false);
		document.addEventListener('touchstart', documentTouchStartHandler, false);
		document.addEventListener('touchmove', documentTouchMoveHandler, false);
		window.addEventListener('resize', windowResizeHandler, false);
		
		createParticles();
		
		windowResizeHandler();
		
		setInterval( loop, 1000 / 60 );
	}
}

function createParticles() {
	particles = [];
	
	for (var g = 0; g < GROUPS.length; g++) {
	    var attribs = GROUPS[g];
	    for (var i = 0; i < attribs.QUANTITY; i++) {
		    var particle = {
			    size: 1,
			    position: { x: mouseX, y: mouseY },
			    offset: { x: 0, y: 0 },
			    shift: { x: mouseX, y: mouseY },
			    speed: 0.01+Math.random()*0.04,
			    targetSize: 1,
			    fillColor: '#' + attribs.COLOR.toString(16),
			    orbit: attribs.RADIUS[0] + 
			           (attribs.RADIUS[1]-attribs.RADIUS[0]) * Math.random()
		    };
		
		    particles.push( particle );
	    }
	}
}

function documentMouseMoveHandler(event) {
	mouseX = event.clientX - (window.innerWidth - SCREEN_WIDTH) * .5;
	mouseY = event.clientY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}

function documentMouseDownHandler(event) {
	mouseIsDown = true;
}

function documentMouseUpHandler(event) {
	mouseIsDown = false;
}

function documentTouchStartHandler(event) {
	if(event.touches.length == 1) {
		event.preventDefault();

		mouseX = event.touches[0].pageX - (window.innerWidth - SCREEN_WIDTH) * .5;;
		mouseY = event.touches[0].pageY - (window.innerHeight - SCREEN_HEIGHT) * .5;
	}
}

function documentTouchMoveHandler(event) {
	if(event.touches.length == 1) {
		event.preventDefault();

		mouseX = event.touches[0].pageX - (window.innerWidth - SCREEN_WIDTH) * .5;;
		mouseY = event.touches[0].pageY - (window.innerHeight - SCREEN_HEIGHT) * .5;
	}
}

function windowResizeHandler() {
	SCREEN_WIDTH = window.innerWidth;
	SCREEN_HEIGHT = window.innerHeight;
	
	canvas.width = SCREEN_WIDTH;
	canvas.height = SCREEN_HEIGHT;
}

function loop() {
	
	if( mouseIsDown ) {
		RADIUS_SCALE += ( RADIUS_SCALE_MAX - RADIUS_SCALE ) * (0.02);
	}
	else {
		RADIUS_SCALE -= ( RADIUS_SCALE - RADIUS_SCALE_MIN ) * (0.02);
	}
	
	RADIUS_SCALE = Math.min( RADIUS_SCALE, RADIUS_SCALE_MAX );
	
	context.fillStyle = 'rgba(0,0,0,0.05)';
		 context.fillRect(0, 0, context.canvas.width, context.canvas.height);
	
	for (i = 0, len = particles.length; i < len; i++) {
		var particle = particles[i];
		
		var lp = { x: particle.position.x, y: particle.position.y };
		
		// Rotation
		particle.offset.x += particle.speed;
		particle.offset.y += particle.speed;
		
		// Follow mouse with some lag
		particle.shift.x += ( mouseX - particle.shift.x) * (particle.speed);
		particle.shift.y += ( mouseY - particle.shift.y) * (particle.speed);
		
		// Apply position
		particle.position.x = particle.shift.x + Math.cos(i + particle.offset.x) * (particle.orbit*RADIUS_SCALE);
		particle.position.y = particle.shift.y + Math.sin(i + particle.offset.y) * (particle.orbit*RADIUS_SCALE);
		
		// Limit to screen bounds
		particle.position.x = Math.max( Math.min( particle.position.x, SCREEN_WIDTH ), 0 );
		particle.position.y = Math.max( Math.min( particle.position.y, SCREEN_HEIGHT ), 0 );
		
		particle.size += ( particle.targetSize - particle.size ) * 0.05;
		
		if( Math.round( particle.size ) == Math.round( particle.targetSize ) ) {
			particle.targetSize = 1 + Math.random() * 7;
		}
		
		context.beginPath();
		context.fillStyle = particle.fillColor;
		context.strokeStyle = particle.fillColor;
		context.lineWidth = particle.size;
		context.moveTo(lp.x, lp.y);
		context.lineTo(particle.position.x, particle.position.y);
		context.stroke();
		context.arc(particle.position.x, particle.position.y, particle.size/2, 0, Math.PI*2, true);
		context.fill();
	}
}

window.onload = init;
&#13;
body { 
  background-color: #000000; 
  padding: 0; 
  margin: 0; 
  overflow: hidden;
}
&#13;
<canvas id='world'></canvas>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以定义数组中的颜色,因为您使用的是for循环,您可以将它们编入索引:

var colors = ['#AAAAAA', '#BBBBBB', '#CCCCCC', '#DDDDDD'];
var particle = {
   ...
   fillColor: colors[i],
   ...
}

现在这只适用于前四种颜色,但由于您声明数量为16,因此您可以使用2 for次循环来实现此目的。像这样:

//will run 16 times
for(var i = 0; i < QUANTITY; i++) {
    for(var x = 0; x < 4; x++) {
        var particle = {
            //note that i'm using x here since the array has only 4 keys.
            fillColor: colors[x];
        }
    }
}