如何更改此颜色(纯js)

How to change the color of this (pure js)?

本文关键字:js 颜色 何更改      更新时间:2023-09-26

我正在尝试在我的网站中实现这个鼠标关注:

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

但是我想要自己的自定义颜色,而不是默认显示的颜色。我更改了填充颜色值并能够更改为一种特定颜色,但我想要 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 代码,看看它是否有效,并且只是更改了填充颜色,但它只会显示最后一个粘贴的。

谁能告诉我如何以最简单的方式获得 4 种不同的颜色,我觉得我把这复杂化了,但显然是一个初学者,对此感到相当沮丧?

最后,我希望 4 种不同的颜色跨越不同的半径,我弄乱了不同的 RADIUS 变量,但几乎不可能弄清楚如何在只有一种颜色的情况下完成我想要的。所以每种颜色会有 4 种,我将数量更改为:

var QUANTITY = 16;

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

var RADIUS = 10;

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

有什么建议吗?

你可以用

这些数组替换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 );
    }
}

下面是一个片段:

// 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;
body { 
  background-color: #000000; 
  padding: 0; 
  margin: 0; 
  overflow: hidden;
}
<canvas id='world'></canvas>

定义数组中粒子的设置

// 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 );
}

这将是上述更改的结果。

您可以定义数组中的颜色,因为您使用的是 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];
        }
    }
}