Why does my element appear to be a different color than expected?

I've developed a sleek wind map (check out for reference).

Using a weighted interpolation every 10ms, I generate uVector and vVector data to calculate wind speed. Based on this speed, each point is assigned a specific color as outlined below.

if (weightWS < 13) {
    color = "#ffa500"
}
if (weightWS < 10) {
    color = "#CCCC00"
}
if (weightWS < 7) {
    color = "#008000"
}
if (weightWS < 4) {
    color = "#0000ff"
}
if (weightWS < 1) {
    color = "#800080"
}

The assigned colors are then passed to the animate function stored in drawData[3].

function animate(){
    ctx.beginPath(); 
    ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.closePath();
    
    for(var pointCount=0;pointCount<pointNum;pointCount++){
        let xMid,yMid;
        let xPoint = points[pointCount][0];
        let yPoint = points[pointCount][1];

        if(xPoint < 141 || xPoint >580 || yPoint < 120 || yPoint > 524){
            xPoint = getRandomIntInclusive(141,580);
            yPoint = getRandomIntInclusive(120,524);
            points.push([xPoint,yPoint]);
        }

        var drawData = weightAllData(xPoint,yPoint);
        colorArr[pointCount] = drawData[3]; 
        
        ctx.moveTo(xPoint, yPoint);
        ctx.lineTo(xPoint+drawData[1],yPoint+drawData[2]);
        ctx.strokeStyle = drawData[3]; 

        ctx.stroke(); 
        points[pointCount][0] = xPoint+drawData[1];
        points[pointCount][1] = yPoint+drawData[2];
    }
}

Despite console feedback displaying various colors, mainly "#800080" and "#0000ff", all points seem to be affected by the same color. Even those with speed above 1 end up purple ("#800080").

The intention is for each individual pixel to have its own color, which should include some blue ("#0000ff") ones. However, any blue points that show up affect all pixels simultaneously, contrary to the desired outcome.

This issue persists regardless of the animation speed setting (e.g. 10ms, 1000ms, 10000ms). Any insights or solutions would be greatly appreciated!

Thank you deeply for your assistance and dedication.

Answer №1

The issue arises from adding path segments to the same path within a for loop.

Consider the code snippet below which includes two loops. The first loop adds 100 path segments to one path, resulting in all lines being redrawn each time `stroke()` is called. Additionally, all path segments are drawn in the last color used, making it very inefficient as the top loop ends up drawing 5050 line segments; the 1st pass draws 1 line, the 2nd pass draws 2 more, and so on.

In contrast, the second loop starts a new path inside the loop where each path segment receives a different color, resulting in only 100 line segments being drawn.

const ctx = canvas.getContext("2d");
ctx.lineWidth = 2;
const colors = ["Green", "Blue", "Red", "Black", "Yellow"];

ctx.beginPath();              // start a new path
for (let i = 0; i < 100; i ++) {
    ctx.strokeStyle = colors[i % colors.length];
    ctx.moveTo(i * 5, 0);    // adds to existing path
    ctx.lineTo(i * 5, 40);
    ctx.stroke();            // draw all path segments since last beginPath
}


for (let i = 0; i < 100; i ++) {
    ctx.strokeStyle = colors[i % colors.length];
    ctx.beginPath();         // start a new path
    ctx.moveTo(i * 5, 60);   // adds to the path
    ctx.lineTo(i * 5, 100);
    ctx.stroke();            // draw the path
}
canvas {boarder: 2px solid #000}
<canvas id="canvas" width="500" height="100></canvas>

It is important to note that whenever you change the style, line width, etc., starting a new path is necessary.

Answer №2

To make the code more efficient, it would be better to use else ifs instead of if statements and replace them with ranges as variables. Here's a revised version of your code:

if (weightWS <= 13 && weightWS > 10) {
            color = "#ffa500"
        }
        else if (weightWS <= 10 && weightWS > 7) {
            color = "#CCCC00"
        }
        else if (weightWS <= 7 && weightWS > 4) {
            color = "#008000"
        }
        else if (weightWS <= 4 && weightWS > 1) {
            color = "#0000ff"
        }
        else if (weightWS <= 1 && weightWS > 0) {
            color = "#800080"
        }
        else {
            color = "#000000")
        }

If this solution works effectively, consider defining variables such as purple = [0, 1]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am seeking to retrieve data from MongoDB by utilizing the limit feature, while also sending a specific query

I'm currently facing some confusion with the limit functionality in MongoDB. I want my code to specifically retrieve data for just two hotels by sending a query request from the backend. export const getHotels = async (req, res, next) => { try ...

Ways to retrieve every element inside a specific div container

Is there a way to select all elements inside a div except for specific ones? For example, consider the following structure: <div id="abc"> <div class="def"> sagar patil</div> <div class="pqr"> patil</div& ...

Encountering a "SyntaxError: Unexpected token '/' in... index.ejs while compiling ejs" issue following the recent npm package updates

After upgrading EJS from version 2.7.4 to 3.1.5 along with some other packages in my project, I am encountering a problem where I can no longer access any of the webpages. Instead, an error is being thrown on every page. Additionally, after the update, I s ...

Issues with Contenteditable functionality in JavaScript

My goal is to make a row editable when a button is clicked. $(":button").click(function(){ var tdvar=$(this).parent('tr').find('td'); $.each(tdvar,function(){ $(this).prop('contenteditable',true); }); }); <s ...

Is it possible for AJAX JSON response to return both accurate and undefined values sporadically?

In the process of developing JavaScript code to pinpoint the smallest unused number within a specified range of numbers, I encountered an issue with the AJAX request. Despite successfully retrieving all used numbers in the designated range, some undefined ...

What are some ways to monitor the movement of elements and activate functions at precise locations?

I am working on a project that involves a #ball element which, when clicked, utilizes jQuery animate to move downwards by 210px. The code I currently have is as follows: $('#ball').click(function() { $(this).animate({ top: '+=2 ...

Is there a way to eliminate the transform style from a draggable element?

I am looking to enhance the CDK drag and drop example by adding a preview of the dragged element with specific left and top positions, without utilizing the transform style. HTML <div class="example-boundary"> <div class="example- ...

Working with jQuery: Creating multiple lightboxes using the same jQuery code

Is there a way to create a universal lightbox with the same code for all lightbox functions on the page using JQuery? $(document).ready(function() { $('.lightbox').click(function() { $('.backdrop, .box').animat ...

React SVG not displaying on page

I am facing an issue with displaying an SVG in my React application. Below is the code snippet: <svg className="svg-arrow"> <use xlinkHref="#svg-arrow" /> </svg> //styling .user-quickview .svg-arrow { fill: #fff; position: ...

Looking to create a clone of an HTML element, make some modifications, and extract the HTML string without impacting the DOM?

After working with some HTML code, I encountered the following: <div style="background:red;width:900px;height:200px" id="wrap"> <div id="inner" style="width:300px;float:left"> ... </div> </div> The tasks at hand are ...

The call signatures for `node-fetch -- typeof import("[...]/node-fetch/index")'` are not properly defined

Originated from this source: https://github.com/node-fetch/node-fetch#json ... my personal code: const fetch = require('node-fetch'); async function doFetch() { const response = await fetch('https://api.github.com/users/github'); ...

AngularJS allows you to toggle the visibility of a div at set intervals, creating

I am struggling with the task of showing and hiding a div that serves as an alert for my application. Currently, I am using $interval to create a continuous show and hide action on the div. However, what I aim for is to have the DIV visible for X amount o ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

Unable to find '/images/img-2.jpg' in the directory 'E:React eact-demosrc'

My code is giving me trouble when trying to add an image background-image: url('/images/img-2.jpg'); An error occurred during compilation. ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src?? ...

What is the best way to utilize an array that has been generated using a function?

After creating a customized function that generates an array of numbers, I encountered an issue where the array is not accessible outside the function itself. function customArrayGenerator (length, order){ // length = array length; order = integer order o ...

A novel RxJS5 operator, resembling `.combineLatest`, yet triggers whenever an individual observable emits

I am searching for a solution to merge multiple Observables into a flattened tuple containing scalar values. This functionality is similar to .combineLatest(), but with the added feature that it should emit a new value tuple even if one of the source obser ...

Adjust the width of a div in Angular 6 based on a specified condition

I need to adjust the width of a div based on certain conditions. <div [ngStyle]="'width': selectedTab =='Home' ? '50%' : '100%'"> </div> The currently selected tab is stored in "selectedTab". There ...

The combination of jQuery, using .load method in javascript to prevent scrolling up, making XMLHttpRequest requests, updating .innerHTML elements, and troubleshooting CSS/JS

While utilizing this code, CSS and Javascript are disabled (only HTML loads): function loadContent(limit) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status ...

Display a confirmation modal before triggering $routeChangeStart in AngularJs, similar to the window.onbeforeunload event

When a user chooses to stay on the page as the route starts to change, the original route remains intact but the form directives are reloaded. This results in the loss of all checkbox and input values, resetting them to their defaults. If a user closes th ...

Validating properties of a class using Typescript's Class-Validator

I tried using the class-validator decorator library for validation processes on my sample project. However, it doesn't seem to be working as expected. The sample project aims to create projects based on user inputs, and I'm attempting to validate ...