Is there a way for me to manipulate the RGB values of the canvas in such a manner that the Red and Green components of the gradient are determined by dividing the position of my mouse cursor

My homework assignment requires using RGB colors where the red value is set to 0, green is the x-coordinate divided by 2, and blue is the y-coordinate divided by 2. I've been trying to control the colors on a canvas using addColorStop functions, but I'm struggling to make the colors change as needed. Any assistance on how to achieve this would be greatly appreciated, as I've been stuck on it for the past 2 days. Thank you.

<!DOCTYPE html>
<html>
<body>
<canvas id="big" onclick="myFiller(event);" width="512" height="512" style="border: solid #000000;"></canvas>
<canvas id="small" width="100" height="100" style="background-color: #FF0000;"></canvas>
<p id="para"></p>
<script>
// add eventListener
  var c = document.getElementById("big");
  var ctx = c.getContext("2d");
  var rgbCanvas = ctx.createLinearGradient(c.width, c.height, 120,120);
  rgbCanvas.addColorStop(0, "red");
  rgbCanvas.addColorStop(0.5 ,"green");
  rgbCanvas.addColorStop(1, "blue");
  ctx.fillStyle = rgbCanvas;
  ctx.fillRect(0,0, 512, 512);

  var s = document.getElementById("small");
  var stx = s.getContext("2d");

  function myFiller(event) {
    console.log("running");
      // document.getElementById("big").innerHTML = style
    //  console.log(cData);
        var x = event.offsetX;
        var y = event.offsetY;
        var pixelContainer = ctx.getImageData(x, y, 1, 1).data; 
        console.log(pixelContainer); 
        console.log(pixelContainer[0],pixelContainer[1],pixelContainer[2],pixelContainer[3])
        
        document.getElementById("big").innerHTML = "(" + pixelContainer[0] + " " + ")";
        var red = (pixelContainer[0]).toString(16);
        var green = (pixelContainer[1]).toString(16);
        var blue = (pixelContainer[2]).toString(16);
        document.getElementById("para").innerHTML = "#"+ red+green+blue;

  }
</script>

</body>

</html>

Answer №1

This code provides a simple method for changing the background color of a canvas element when the mouse is moved.

Reference: MDN documentation on mousemove event

  document.querySelector('canvas').addEventListener('mousemove', evt => 
    evt.target.style.backgroundColor = `rgb(${evt.offsetX / 2}, ${evt.offsetY / 2}, 0)`
  )
<!DOCTYPE html>
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <canvas width="512" height="512"></canvas>
  </body>
</html>

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

What is the most efficient method for storing and retrieving numerous DOM elements as JSON using the FileSystem (fs) Module in Node.js?

Is there a way to efficiently save dynamically added DOM elements, such as draggable DIVs, to a file and then reload them later on? I am looking for the most organized approach to achieve this. ...

Issue with Safari not displaying properly when using float:left and float:right (works fine in Firefox and Chrome)

My website has a left side column and a right side column, which display correctly in Firefox and Chrome. However, I am experiencing issues with Safari. Any insights on what could be causing this problem and why it only occurs in Safari? View the code on ...

Combining Summernote images with Node.js using Express.js

While there are numerous solutions available for handling the Summernote file-upload in PHP, I have struggled to find a satisfactory solution for Node.js. Here is My JavaScript: $(document).ready(function() { // $('#summernote').summernote( ...

Exposing the secrets of the Ajax module

Here is the code snippet I am working with: my.data = function () { var getAuth = function (userName, password) { var model = JSON.stringify({ "UserName": userName, "Password": password }); var result; $.ajax({ url: m ...

"Losing focus: The challenge of maintaining focus on dynamic input fields in Angular 2

I am currently designing a dynamic form where each Field contains a list of values, with each value represented as a string. export class Field { name: string; values: string[] = []; fieldType: string; constructor(fieldType: string) { this ...

Saving Information from an HTML Form Input?

I am currently working on a form that collects information about employees including their name, age, position, and details. When the "Add Record" button is pressed, this information should be added to a designated div. Although I have set up the Object C ...

Having trouble getting CSS Animation to work in a React project?

I am currently developing a Next.js application using React. const partyButton = useRef(null) const handleParty = () => { setTimeout(() => { partyButton.current.classList.add('party-time'); console.log(party ...

Injecting data into a Q promise

I'm facing some issues related to what seems like JavaScript closures. In my Express + Mongoose web application, I am utilizing the Q library for Promises. I have a question regarding passing request data to the promise chain in order to successfully ...

Extract the price value from the span element, then multiply it by a certain number before adding it to a div element

On the checkout page of my website, I have the following HTML: <tr class="order-total"> <th>Total</th> <td><strong><span class="woocommerce-Price-amount amount"> <span class="w ...

Issues with HTML Email display

Hey there, I am facing an issue while trying to send an HTML email. I am aware that Outlook does not support a lot of CSS formatting, but I can't figure out why this simple setup is breaking. Is there a quick fix or alternative solution? Take a look a ...

An issue is preventing the Angular 2+ http service from making the requested call to the server

I am looking to create a model class that can access services in Angular. Let's say I have the following endpoints: /book/:id /book/:id/author I want to use a service called BooksService to retrieve a list of Book instances. These instances should ...

Can you explain the meaning of this AJAX code snippet?

I've been researching online for information, but I'm struggling to find any details about the AJAX code snippet that I'm using: function getEmployeeFilterOptions(){ var opts = []; $checkboxes.each(function(){ if(this.checke ...

How to retrieve the context of a .js file using jQuery $.ajax without automatically executing upon receipt

Upon fetching a *.js file using $.ajax, the scripts are executed upon receipt! Is there a way to fetch and execute it only when desired? Moreover, is there a method to remove these scripts at will? ...

Transform the binary image data sent by the server into an <img> element without using base64 encoding

It's been a challenge trying to find a reliable method for adding custom request headers to img src, so I'm experimenting with manually downloading the image using ajax. Here is an example of the code I am working on: const load = async () => ...

Guide to implementing server-side data loading in App.js using Next.js

Is there a way to fetch the layout data along with the page without adding it to every individual page? The issue I'm facing is that my layout component, loaded once on App.jsx, remains consistent throughout the session. However, due to SSRed page loa ...

JavaScript is reliant on the presence of the alert() function to properly function

I have a JavaScript function that performs well, except for when I remove or comment out the alert() line. This function is designed to calculate the sum of values in up to 30 fields if they are present and contain a value. Here is an example of the HTML ...

Preventing Adjacent Text from Moving Due to a Floated i Element

I have a div with a bootstrap icon positioned at the top right corner. However, I want to center the text horizontally without shifting the position of the icon. Is there a way to achieve this? See my sample code here: https://jsfiddle.net/x1Lvyu6t/3/ ...

Tips on transferring a Rails variable to Ajax

Struggling to integrate a progress bar (Javascript) into my Ruby on Rails application, I am facing difficulties in passing values from the controller to JS for updating the bar. In my initial attempt, I used a basic global variable ($count), but it remain ...

I am experiencing an issue with my Node.js query, as it is not successfully adding a user to my database using

I'm currently working on developing an API using Node.JS, express, and MySQL with the Sequelize ORM. I wanted to do this project properly without relying on the CLI for every task. However, I've encountered a problem where my API fails to create ...

Refine JSON data by selecting only distinct key/value pairs

My JSON object has the following structure: var theSchools = { Bradley University: "bru", Knox College: "knox", Southern Illinois University Edwardsville: "siue",… } I am trying to find a way to retrieve the school name (key) based on the schoo ...