I have this method to generate me random colors for font:
function getRandomRolor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
The problem is that the font is always on white background, I want to generate dark colors.
Is it possible?
Thanks
As you know RGB at 0,0,0 is black the darkest and it goes toward getting light until (255,255,255) so you can stop it to go above 100, to get only dark colors or say 9 in hex:
Here is jsFiddle
function getDarkColor() {
var color = '#';
for (var i = 0; i < 6; i++) {
color += Math.floor(Math.random() * 10);
}
return color;
}
Take any random digit from 0-5 as the first digit of your color and then choose the rest of the five digits using your above code.
JS Fiddle: http://jsfiddle.net/xP5v8/
var color,
letters = '0123456789ABCDEF'.split('')
function AddDigitToColor(limit)
{
color += letters[Math.round(Math.random() * limit )]
}
function GetRandomColor() {
color = '#'
AddDigitToColor(5)
for (var i = 0; i < 5; i++) {
AddDigitToColor(15)
}
return color
}
You could use a custom function that takes a hex and darkens it by the percent lum. You can modify it to return whatever you want back
function ColorLuminance(hex, lum) {
// validate hex string
hex = String(hex).replace(/[^0-9a-f]/gi, '');
if (hex.length < 6) {
hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
}
lum = lum || 0;
// convert to decimal and change luminosity
var rgb = "#", c, i;
for (i = 0; i < 3; i++) {
c = parseInt(hex.substr(i*2,2), 16);
c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
rgb += ("00"+c).substr(c.length);
}
return rgb;
}
You could also just use hsl (Hugh, Saturation, Luminosity or Lightness). The hsl link actually goes through the above code.
// seperate array by index
// [0, 1, 2, 3], 2 => [2, 3, 1, 0]
function tail(arr, ind){
let mhs, lhs;
if(arr.length / 2 > ind){
mhs = arr.length - 1 - ind;
lhs = ind;
}else{
mhs = ind;
lhs = arr.length - 1 - ind;
}
let nd = [arr[ind]];
for(let i = 0; i < lhs; i++){
nd.push(arr[ind+i+1]);
nd.push(arr[ind-i-1]);
}
for(let i = 0; i < mhs - lhs; i++){
nd.push(arr[i]);
}
return nd;
}
// yield optimization
// 6=>6 6=>3
// 5=>5 5=>3
// 4=>4 4=>2
// 3=>3 3=>2
// 2=>2 2=>1
// 1=>1 1=>1
// 21 12
function dense(len, den){
let st = Math.ceil(len / den);
let nd = [];
for(let i = 0; i < st; i++){
for(let j = 0; j < den; j++){
nd.push(st - i);
}
}
if(len % 2 !== 0){
nd.shift();
}
return nd;
}
// shift the weight to certain part of array by index
// de controls the rate of differing
function shift_weight(arr, ind, de){
let ta = tail(arr, ind);
let nd = [];
let den = dense(arr.length, de)
for(let i = 0; i < ta.length; i++){
for(let j = 0; j < den[i]; j++){
nd.push(ta[i]);
}
}
return nd;
}
function parseDarkHex(den){
let hexcode = '0123456789abcdef';
let ocean = shift_weight(Array.from({length: 16}, (x, i) => hexcode[i]), 0, den);
return '#' + Array.from({length: 6}).map(ud=>ocean[Math.floor(Math.random() * ocean.length)]).join('');
}
function parseLightHex(den){
let hexcode = '0123456789abcdef';
let ocean = shift_weight(Array.from({length: 16}, (x, i) => hexcode[i]), 16, den);
return '#' + Array.from({length: 6}).map(ud=>ocean[Math.floor(Math.random() * ocean.length)]).join('');
}
// 2~8, the smaller the more accurate, the larger the faster
console.log(parseDarkHex(4))
// #51baaa
// #046d1c
// #003183
This allows the existence of large hex value such as f, c, b, etc, but at a low occurrence.
1500 bytes for you. But works awesome!
I don't think my solution is represented here, so I will add it in (even though I am very late to the game).
I am just subtracting from the 255 random range on each value. Seems to work well and is very simple. If you wanted RandomColorLight, just add the offset value to the random result of each component.
You can also combine the two into one RandomColorRange method very easily.
public static Color RandomColorDark(int offset)
{
var maxValue = 256 - offset;
return Color.FromArgb(_random.Next(maxValue), _random.Next(maxValue), _random.Next(maxValue));
}
public static Color RandomColorLight(int offset)
{
var maxValue = 256 - offset;
return Color.FromArgb(_random.Next(maxValue) + offset, _random.Next(maxValue) + offset, _random.Next(maxValue) + offset);
}
Sorry, my solution is not javascript. It is C#, but the logic should be easy enough to understand.
Related
How to extract elements of a matrix in a particular pattern using javascript?
following is the code for generating a 2d matrix of size any
var matrix = [];
for(var i=0; I<size; i++) {
matrix[i] = [];
for(var j=0; j<size; j++) {
matrix[i][j] = undefined;
}
}
so the first one is the original matrix. second one is the matrix made out by removing some elements/ cells.
// don't worry about splicing... this is just a demo.
[[3,5], [4,5], [4,2] ... ].forEach(([i,j], _, arr) => delete arr[i][j])
***** This is where you begin *****
(from the above splices matrix the following has to be done)
so what I want to achieve is that I want to separate or group cells from the above spliced matrix in the following manner. (like concentric circles/squares fashion by keeping in mind the fact that some cells are removed)
first you start at the central element [i,j], then move to the next level 3 x 3 & assign a value to all concentric cells (or separate cell address out)... then move to the next level 4 x 4 assign a value to all concentric cells (or separate cell address out) and so on...
Note that the spliced matrix is the starting point
travel in this fashion outwards (like concentric squares):
the idea is that:\
generate a matrix of size n * n.
remove some elements (that will be any)
... from here the algorithm starts...
separate cells from the above splices matrix in a concentric square fashion. --> this is where I want help (step 3 only)
In simple terms I want to separate out the cells from the matrix in the following order (one level at a time 3 x 3 first then 4 x 4 then 5 x 5 and so on.... ( from the above spliced matrix, which means that some cells will be already removed.)
keep in mind the fact that some cells are already removed (so you'll have to skip them -)
First, figure out the centroid of the square. The center is going to be at {length / 2, width / 2}. We're dealing in integer units, so floor. Using the convention that the top left of the figure is {0, 0} , then ie a 7x7 square has its center at
{floor(7/2), floor(7/2)} === {3,3}
Then, figure out a distance formula. In the pictures, the unit squares in purple are all the squares where either the x coordinate or y coordinate are N units away from the center. In other words
max(x - centerX, y-centerY) === N
I agree with #audzzy, you don't want to delete anything since that actually changes the length of an individual row, which we don't want. Instead just set it to another value.
So the idea is to:
find the center
iterate over each unit square
clear any unit squares which are N distance from the center
const clearCircle = (mat, N) => {
// find the center
const maxI = mat.length, maxJ = mat[0].length,
center = {
i: Math.floor(mat.length / 2),
j: Math.floor(mat[0].length / 2)
};
// iterate over all units
for (let i = 0; i < maxI; i++) {
for (let j = 0; j < maxJ; j++) {
// check if its N units from the center
if (Math.max(Math.abs(center.i - i), Math.abs(center.j - j)) === N) {
mat[i][j] = " ";
}
}
}
return mat;
}
Full example:
/*jshint esnext: true */
const generateMat = size => {
const mat = [];
for (let i = 0; i < size; i++) {
mat[i] = [];
for (let j = 0; j < size; j++) {
mat[i][j] = "[ ]";
}
}
return mat;
}
const mat = generateMat(9);
const logMat = mat => console.log("\n" + mat.map(row => (row).join(" ")).join("\n") + "\n");
const clearCircle = (mat, N) => {
// find the center
const maxI = mat.length, maxJ = mat[0].length,
center = {
i: Math.floor(mat.length / 2),
j: Math.floor(mat[0].length / 2)
};
// iterate over all units
for (let i = 0; i < maxI; i++) {
for (let j = 0; j < maxJ; j++) {
// check if its N units from the center
if (Math.max(Math.abs(center.i - i), Math.abs(center.j - j)) === N) {
mat[i][j] = " ";
}
}
}
return mat;
}
logMat(mat);
logMat(clearCircle(mat, 1));
logMat(clearCircle(mat, 2));
logMat(clearCircle(mat, 3));
Well... you just need exclude squares outside boundaries, after that you can just select elements which are in the most external layer of the matrix!
Something like that:
function extractElements(layer, matrix) {
const elements = []
const n = matrix.length; // matrix NxN
const frontIndex = layer -1;
const backIndex = n - layer;
if(layer <= 0 || layer > Math.ceil(n/2)) {
console.log("invalid layer");
return [];
}
for(let i = 0; i < n; ++i){
if(i < frontIndex || i > backIndex)
continue;
for(let j = 0; j < n; ++j){
if(j < frontIndex || j > backIndex)
continue;
if(i === frontIndex || i === backIndex || j === frontIndex || j === backIndex) {
if(matrix[i][j] !== undefined)
elements.push(matrix[i][j]);
}
}
}
return elements;
}
So, if you want the most external layer of a matrix 5x5, you can call extractElements(1, matrix)
Good code!
here's some basic code to do what you want (here I colored the cells, you could add them to a result array, or do whateve else you want)
notice it has very little iterations- only goes over the "wanted" cells every time- and colors the relevant lines and columns,
(for visual reasons -
'-' is a regular cell,
' ' is deleted cell,
'a' is a "purple" cell)
setMatrix is basically the interesting part that gets the interesting cells of every level..
let setMatrix = (matrix, level, value) => {
let size = matrix.length;
for(let x=Math.floor(size/2)-level;x<=Math.floor(size/2)+level;x++){
matrix[x][Math.floor(size/2)-level] = matrix[x][Math.floor(size/2)-level] == ' ' ? ' ' : value;
matrix[x][Math.floor(size/2)+level] = matrix[x][Math.floor(size/2)+level] == ' ' ? ' ' : value;
if(x!=Math.floor(size/2)-level && x!=Math.floor(size/2)+level){
matrix[Math.floor(size/2)-level][x] = matrix[Math.floor(size/2)-level][x] == ' ' ? ' ' : value;
matrix[Math.floor(size/2)+level][x] = matrix[Math.floor(size/2)+level][x] == ' ' ? ' ' : value;
}
}
}
and here's some code to call it for each level:
function doWork(){
// init
let size = 7;
var matrix = [];
for(var i=0; i<size; i++) {
matrix[i] = [];
for(var j=0; j<size; j++) {
matrix[i][j] = '-';
}
}
// delete
[[1,1], [2,3], [2,5], [5,1], [6,4]].forEach(([i,j])=> matrix[i][j] = ' ');
// go over each level
for(let i=0;i<=Math.floor(size/2);i++){
// set
setMatrix(matrix, i, 'a');
// print
for(let x=0;x<size;x++){
let line='';
for(let y=0;y<size;y++){
line+=matrix[x][y];
}
console.log(line);
}
console.log();
//reset
setMatrix(matrix, i, '-');
}
}
doWork();
last stone weight 2 solution in cpp
This is able to pass all test cases.
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int n = stones.size();
int total = 0;
for(int i = 0; i < n; i++){
total += stones[i];
}
int req = total / 2;
vector <bool> dp(req + 1, false);
dp[0] = true;
int reach = 0;
for(int i = 0; i < n; i++){
for(int j = req; j - stones[i] >= 0; j--){
dp[j] = dp[j] || dp[j - stones[i]];
if(dp[j]) reach = max(reach, j);
}
}
return total - (2 * reach);
}
};
I tried to replicate it in javascript and not able to pass
a simple test cases like [2,7,4,1,8,1]
Here is my attempt
var lastStoneWeightII = function(st) {
// stone #
const n = st.length;
// sum up
const sum = st.reduce((acc, curr) => {return acc+curr});
// e.g. half
const ha = Math.floor(sum / 2);
// half+1
const dp = Array(ha+1).fill(false);
// 1st ele = true
dp[0] = true;
// store tmp_max
let max = 0;
// loop element
for(let i=0; i<n; i++) {
// single element
const w = n[i];
// backward, half
for(let j=ha; j-w>=0; j--) {
// update condi
dp[j] = dp[j] || dp[j-w];
// never comes in
if(dp[j]) {
//test
console.log('++++ max', max, 'j', j)
max = Math.max(max, j);
}
}
}
return (sum - max) - max;
}
I've tried to use this code:
function calc (n, c) {
let a = 0
const omega = Math.pow(2, n)
let search1 = ''
let search2 = ''
for (let i = 0; i < c; i++) {
search1 += '0'
}
for (let i = 0; i < c; i++) {
search2 += '1'
}
for (let i = 0; i < omega; i++) {
if (i.toString(2).includes(search1) || i.toString(2).includes(search2)) {
a++
}
}
const prob = a * 100 / omega
console.log({ a: a, omega: omega, prob: prob.toFixed(2) })
}
calc(1000, 8)
Which works, but is slow when it comes to big numbers. How can I optimize my code to make it faster? Or maybe there exists a Mathematical solution, that doesn't require to code at all? I just want to know the solution for this problem.
First a Monte Carlo simulation answer:
You can find a confidence interval for this simulation by doing some statistical inference on the Bernoulli distribution which I won't do here.
function doesItHappen(l,r){
var lastValue = null;
var lastN = 0;
for(var i = 0; i < l; i++){
var currentValue = Math.random() > 0.5 ? 1 : 0;
if(lastValue === currentValue) {
lastN++;
} else {
lastValue = currentValue;
lastN = 1;
}
if(lastN === r) return true;
}
return false;
}
function rep(n,l,r){
var t = 0;
for(var i = 0; i < n; i++) {
if(doesItHappen(l,r)) t++;
}
return t/n;
}
console.log(rep(100000,1000,8))
Finally the actual Mathematical answer
I couldn't find a solution to this question online so I came up with my own method to calculate this in o(n) time and space complexity, you can even get it down to o(1) space complexity by discarding valueStore objects older than the length of consecutive sequence you want. The key thing is to recognise you have to computer all the combinations prior to the current length, similar to a Fibonacci sequence.
function calculateProbability(l,r) {
var valueStore = [
{ // Initialize it
totalNumberOfCombinations: 2,
numberOfCombinationsWithSequence: 0
}
];
function getValues(index) {
// combinations with the sequence in it
// There are two ways a consecutive sequence of r length can occur, it either occured in the previous combination and we flipped a new heads or tails(doesn't matter)
// Or this flip resulted in a new consecutive sequence of r length occuring (let's say theres k combinations of this)
// Heres the genius, k must end in a sequence of heads or tails so theres 2 possible endings, the beginnings of k cannot contain the sequence of r consecutive flips
// If this previous combination ends in a head then the new sequence is all tails and vice versa
// So k = the combinations of flips without the consective flips before the current sequence
// k = the totalNumberOfCombinations 8 flips ago - numberOfCombinationsWithSequence 8 flips ago
if (index === r - 1) {
// All heads or all tails
var numberOfCombinationsWithSequence = 2;
} else if(index < r) {
var numberOfCombinationsWithSequence = 0;
} else {
var numberOfCombinationsWithSequence = valueStore[index - 1].numberOfCombinationsWithSequence * 2 + (valueStore[index - r].totalNumberOfCombinations - valueStore[index - r].numberOfCombinationsWithSequence)
}
return {
// total possible combinations
// this is just the previous number of combinations but times 2 since we flip again
totalNumberOfCombinations: valueStore[index - 1].totalNumberOfCombinations * 2,
numberOfCombinationsWithSequence: numberOfCombinationsWithSequence
}
}
for(var i = 1; i < l; i++) {
var values = getValues(i);
valueStore.push(values);
}
return valueStore[valueStore.length - 1].numberOfCombinationsWithSequence / valueStore[valueStore.length - 1].totalNumberOfCombinations;
}
console.log(calculateProbability(1000,8));
The 100% accurate answer is 0.9817098435878764 or 98.17%
how about a simulation?
function simulate(throws, streak, runs) {
let win = "".padStart(streak, "1")
let win2 = "".padStart(streak, "0")
let hits = 0
for (let n = 0; n < runs; n++) {
let res = "";
for (let i = 0; i < throws; i++) {
let val = Math.round(Math.random())
res += val
}
if (res.includes(win) || res.includes(win2)) {
hits++
}
}
console.log({
hits,
runs,
prob: ((hits / runs) * 100).toFixed(2)
})
}
simulate(1000, 8, 10000)
EDIT: I KIND OF FIGURED IT OUT CODE HERE STILL SOME ISSUES (has to be 255 objects right now):
for (let i = 1; i <= 255; i++) {
let arg = document.createElement("div");
let red = 0;
let green = 0;
let blue = 0;
if (color == 0) {
red = 255;
green = num * 3;
} else if (color == 1) {
red = 255 - num*3;
green = 255;
blue = num * 3;
} else if (color == 2) {
red = num * 3;
green = 255-num*3;
blue = 255;
}
arg.style.backgroundColor = "#" + htd(red) + htd(green) + htd(blue);
document.querySelector("body").appendChild(arg);
if (num == 85) {
num = 1;
color++;
} else {
num++;
}
}
OLD QUESTION
I am generating a number of HTML objects in JS using a for loop. I want these objects to progressively be colored from red to purple (rainbow order). How would I go about going from #FF0000 to #008080 and back again to #FF0000.
Here is my code so far (DOESN'T WORK WELL):
for (let i = 1; i < 255; i++) {
let arg = document.createElement("div");
let num = i;
if (num > 255) {
num = 255;
}
let red = 255;
let blue = 0;
if (num < 128) {
let green = 0;
arg.style.backgroundColor = "#" + htd(red - i) + htd(green + i * 2) + htd(blue + i);
} else {
let green = 256;
arg.style.backgroundColor = "#" + htd(red - i * 2) + htd(green - i * 2) + htd(blue + i);
}
document.querySelector("body").appendChild(arg);
}
function htd(num) {
let hexString = num.toString(16);
if (hexString.length % 2) {
hexString = '0' + hexString;
}
return hexString;
}
If you want to see why I need this go to https://codepen.io/navinate/pen/dwExxm
Thank You!
What I think you want is
A gradient of hue values
A conversion from HSL (hue, saturation, lightness) to RGB
RGB to #hex notation, which you already have covered
A gradient of hues is a simple linear interpolation problem:
const length = 100;
const hueGradient = Array.from({length}, (v, k) => k/(length-1));
A sample conversion from HSL to RGB can be found in an answer to this question. Using that:
const saturation = 1.0;
const lightness = 0.5;
const rgbValues = hueGradient.map(hue => hslToRgb(hue, saturation, lightness));
The result is an array of [R, G, B] which you can express as #rgb values:
const htmlRgbValues = rgbValues.map(([r,g,b]) => `#${htd(r)}${htd(g)}${htd(b)}`);
There's a good chance that you don't want a lookup table, but instead want to interpolate on the fly, just use
const htmlRgbValue = hslToRgb(x / x_max, saturation, lightness);
So basically, I want to draw a curved average line over a certain amount of points of a time-series line chart. Like this:
I want it to span the entire length of the chart but I can't figure out how to calculate the start and end points because the average would (I think) be a point in the middle of each section. Looking at a stock chart with moving average you can see what I want to acheive:
I calculate the averages first by splitting the data array up into chunks based on a period of time. So if I start with:
[
{ time: 1, value: 2 },
{ time: 2, value: 4 },
{ time: 3, value: 5 },
{ time: 4, value: 7 },
]
I get to:
var averages = [
{
x: 1.5,
y: 3,
},
{
x: 3.5 (the average time)
y: 6 (the average value)
},
]
This is what I've tried where I end up with an incomplete line, one that doesnt start at the beginning of the chart and doesnt stop at the end, but stars and ends inside the chart at the first average time:
ctx.moveTo((averages[0].x), averages[0].y);
for(var i = 0; i < averages.length-1; i ++)
{
var x_mid = (averages[i].x + averages[i+1].x) / 2;
var y_mid = (averages[i].y + averages[i+1].y) / 2;
var cp_x1 = (x_mid + averages[i].x) / 2;
var cp_x2 = (x_mid + averages[i+1].x) / 2;
ctx.quadraticCurveTo(cp_x1, averages[i].y ,x_mid, y_mid);
ctx.quadraticCurveTo(cp_x2, averages[i+1].y ,averages[i+1].x, averages[i+1].y);
}
ctx.stroke();
How would you do this?
To get a moving mean you need to just get the mean of n points either side of the current sample.
For example
// array of data points
const movingMean = []; // the resulting means
const data = [12,345,123,53,134,...,219]; // data with index representing x axis
const sampleSize = 5;
for(var i = sampleSize; i < data.length - sampleSize; i++){
var total = 0;
for(var j = i- sampleSize; j < i + sampleSize; j++){
total += data[j];
}
movingMean[i] = total / (sampleSize * 2);
}
This method does not pull the mean forward giving the most accurate mean for each data point.
The problem with this method is that you do not get a mean for the first n and last n samples, where n is the number of samples either side of the mean.
You can do an alternative that will pull the mean forward a little but by applying a weighted mean you can reduce the bias a little
for(var i = sampleSize; i < data.length + Math.floor(sampleSize / 4); i++){
var total = 0;
var count = 0;
for(var j = sampleSize; j > 0; j --){
var index = i - (sampleSize - j);
if(index < data.length){
total += data[index] * j; // linear weighting
count += j;
}
}
movingMean[i-Math.floor(sampleSize / 4)] = total / count;
}
This method keeps that mean closer to the current sample end.
The example show a random data set and the two types of means plotted over it. Click to get a new plot. The red line is the moving mean and the blue is the weighted mean. Note how the blue line tends to follow the data a little slow.
The green line is a weighted mean that has a sample range 4 times greater than the other two.
// helper functions
const doFor = (count, callback) => {var i = 0; while (i < count) { callback(i ++) } };
const setOf = (count, callback) => {var a = [],i = 0; while (i < count) { a.push(callback(i ++)) } return a };
const rand = (min, max = min + (min = 0)) => Math.random() * (max - min) + min;
const randG = (dis, min, max) => {var r = 0; doFor(dis,()=>r+=rand(min,max)); return r / dis};
function getMinMax(data){
var min = data[0];
var max = data[0];
doFor(data.length - 1, i => {
min = Math.min(min,data[i+1]);
max = Math.max(max,data[i+1]);
});
var range = max-min;
return {min,max,range};
}
function plotData(data,minMax){
ctx.beginPath();
for(var i = 0; i < data.length; i++){
if(data[i] !== undefined){
var y = (data[i] - minMax.min) / minMax.range;
y = y *(ctx.canvas.height - 2) + 1;
ctx.lineTo(i/2,y);
}
}
ctx.stroke();
}
function getMovingMean(data,sampleSize){
const movingMean = []; // the resulting means
for(var i = sampleSize; i < data.length - sampleSize; i++){
var total = 0;
for(var j = i- sampleSize; j < i + sampleSize; j++){
total += data[j];
}
movingMean[i] = total / (sampleSize * 2);
}
return movingMean[i];
}
function getMovingMean(data,sampleSize){
const movingMean = []; // the resulting means
for(var i = sampleSize; i < data.length - sampleSize; i++){
var total = 0;
for(var j = i- sampleSize; j < i + sampleSize; j++){
total += data[j];
}
movingMean[i] = total / (sampleSize * 2);
}
return movingMean;
}
function getWeightedMean(data,sampleSize){
const weightedMean = [];
for(var i = sampleSize; i < data.length+Math.floor(sampleSize/4); i++){
var total = 0;
var count = 0;
for(var j = sampleSize; j > 0; j --){
var index = i - (sampleSize - j);
if(index < data.length){
total += data[index] * j; // linear weighting
count += j;
}
}
weightedMean[i-Math.floor(sampleSize/4)] = total / count;
}
return weightedMean;
}
const dataSize = 1000;
const sampleSize = 50;
canvas.width = dataSize/2;
canvas.height = 200;
const ctx = canvas.getContext("2d");
function displayData(){
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
var dataPoint = 100;
var distribution = Math.floor(rand(1,8));
var movement = rand(2,20);
const data = setOf(dataSize,i => dataPoint += randG(distribution, -movement, movement));
const movingMean = getMovingMean(data, sampleSize);
const weightedMean = getWeightedMean(data, sampleSize*2);
const weightedMean1 = getWeightedMean(data, sampleSize*8);
var minMax = getMinMax(data);
ctx.strokeStyle = "#ccc";
plotData(data,minMax);
ctx.strokeStyle = "#F50";
plotData(movingMean,minMax);
ctx.strokeStyle = "#08F";
plotData(weightedMean,minMax);
ctx.strokeStyle = "#4C0";
plotData(weightedMean1,minMax);
}
displayData();
document.onclick = displayData;
body { font-family : arial; }
.red { color : #F50; }
.blue { color : #0AF; }
.green { color : #4C0; }
canvas { position : absolute; top : 0px; left :130px; }
<canvas id="canvas"></canvas>
<div class="red">Moving mean</div>
<div class="blue">Weighted mean</div>
<div class="green">Wide weighted mean</div>
<div>Click for another sample</div>