I seem to be struggling with creating a masterpiece using this particular color

Description: I've implemented a canvas drawing feature on my webpage with the provided code. Users can select colors and draw, but for some reason, the selected color is not functioning properly. Any assistance in resolving this issue would be greatly appreciated.

p.s. Clicking the button will open up the canvas.

Demo: jsfiddle

<button onClick="openPopup();">click here</button>
    <div id="test" class="popup">
     <div></div>
        <div class="cancel" onclick="closePopup();"></div>
        <canvas id="canvas1" width="750" height="720" style="border: 1px solid black">
        </canvas>

      <p>&nbsp;</p>

      <p>
      <input type="button" id="Orange" style="background-color: orange; width: 25px;
    height: 25px;"/>
    <input type="button" id="Yellow" style="background-color: yellow; width: 25px;
    height: 25px;"/>
    <input type="button" id="Green" style="background-color: green; width: 25px;
    height: 25px;"/>
    <input type="button" id="Blue" style="background-color: blue; width: 25px;
    height: 25px;"/>
    <input type="button" id="Purple" style="background-color: purple; width: 25px;
    height: 25px;"/>
    <input type="button" id="Brown" style="background-color: brown; width: 25px;
    height: 25px;"/>
    <input type="button" id="Black" style="background-color: black; width: 25px;
    height: 25px;"/>
    <input type="button" id="White" style="background-color: white; width: 25px;
    height: 25px;"/>
    </p>

    <p><input type="button" id="reset_image" value="Reset Drawing"/></p>
    </div>

    <style>
    #canvas1 {
        left:0;
        top:0;
    }

    .popup{
        position:absolute;
        top:0px;
        left:0px;
        margin:0px;
        width: 900px;
        height: 750px;
        font-family:verdana;
        font-size:13px;
        background-color:white;
        border:2px solid grey;
        z-index:100000000000000000;
        display:none;
        opacity:0.6;
        filter:alpha(opacity=60);
        margin-left: 300px;
        margin-top: 90px; 
        overflow: auto; 
        }

    .cancel{
        display:relative;
        cursor:pointer;
        margin:0;
        float:right;
        height:10px;
        width:14px;
        padding:0 0 5px 0;
        background-color:red;
        text-align:center;
        font-weight:bold;
        font-size:11px;
        color:white;
        border-radius:3px;
        z-index:100000000000000000;
        }

    .cancel:hover{
        background:rgb(255,50,50);
        }

    </style>
    
    <script>
    function openPopup() {
        var p = document.getElementById('test');
        p.style.display = 'block';

        canvas.width  = parseInt(p.style.width, '10'); //only when you use pixels
        canvas.height = parseInt(p.style.height, '10');
    }
    function closePopup() {
        document.getElementById('test').style.display = 'none';
    }

    var can = document.getElementById('canvas1');
    var ctx = can.getContext('2d');

    var isPressed = false;
    var mx = 4, my = 4;

    function move(e) {
      getMouse(e);
      if (isPressed) {
        ctx.lineTo(mx, my);
        ctx.stroke()
      }
    }

    function up(e) {
      getMouse(e);
      isPressed = false;
    }

    function down(e) {
      getMouse(e);
      ctx.beginPath();
      ctx.moveTo(mx, my);
      isPressed = true;
    }

    can.onmousemove = move;
    can.onmousedown = down;
    can.onmouseup = up;

    // way oversimplified:
    function getMouse(e) {
        var element = can, offsetX = 0, offsetY = 0;
        mx = e.pageX - 305;
        my = e.pageY - 95;

    }  
    </script>

Answer №1

Here is a simple solution to change the color when a button is clicked:

function alterColor(colorParameter) {
ctx.strokeStyle = colorParameter; // selected color
}

Make sure to add an onclick event to each button, like so:

<input type="button" onclick="alterColor('yellow')" id="YellowButton" style="background-color: yellow; width: 25px;
height: 25px;"/>

To see this in action, check out this live demonstration: Live Demo

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 possess controller functions designed to remove a user from the system. My goal is to adhere to the DRY (Don't Repeat Yourself) principle by creating a dynamic response message for the JSON

I am looking to apply the DRY principle to my code snippet for deleting different types of users, and I also want to create a response that dynamically adjusts based on the model details provided to the find method. //The function below is responsible for ...

Create a dynamic and interactive website using a combination of jQuery and AngularJS

I recently came across an interesting tidbit on the FAQs of Angular stating that "Angular can use jQuery if it's present in your app when the application is being bootstrapped". This got me thinking, is it considered a best practice to include both j ...

Exploring the potential of utilizing arguments within the RxJS/map operator

When working with rxjs, export function map<T, R, A>(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction<T, R>; I seem to be struggling to find a practical use for thisArg: A. ...

Warning in React js: [eslint] srcApp.js Line 2:8 - The variable 'person' is declared but not utilized

[![I need assistance with this problem. Whenever I try to resolve it, I consistently encounter the same error on Line 2:8: 'person' is defined but never used - no-unused-vars.][1]][1] ...

CKeditor does not accept special characters or diacritics in keywords

Recently, I came across a helpful code snippet for CKeditor that counts and ranks the most used words in a textarea. This feature is invaluable for generating SEO-keywords suggestions while writing articles. However, there is an issue with non-English char ...

Issue with $http.get in fetching information from PHP server

Dealing with duplicate keys error in AngularJS, PHP, and MySQL I have been working on a web-based system and encountered an issue with ng-repeat displaying duplicate keys. I am unsure how to resolve this issue. The select all brand functionality seems to ...

Can JQuery be used to identify the CSS styles applied to selected elements?

Highlight the text by selecting it and clicking a button. If the text is already highlighted, clicking the button should make the selected text return to normal. Can this be achieved using jQuery and a single button? Is it possible to identify the CSS st ...

The raycasting is running wild, responding without hesitation when it should only be triggered by a

I've encountered an issue with a script I created that is supposed to add a new plane to a scene every time I click on an existing plane using a raycaster for detection. However, the script is adding planes uncontrollably to the scene without any clic ...

What is the best way to fetch the id of the option that has been chosen from a bootstrap drop-down menu?

I recently created a basic drop-down list like this: https://i.sstatic.net/4Tlxx.png Here is the HTML code for it: <select class="form-control" id='0' (change)="retrieveValue($event.target)"> <option id='0'>{{ g ...

Obtain the chosen option from an HTML select element by utilizing JavaScript

This is my HTML snippet: <div id="detail"> <div class="d_left"> Page <strong>1</strong> of 107 </div> <div class="d_center"> <table> <tr> <td><a href="#">Previous&l ...

Error: Dotenv.apply is unable to access the property 'version' because it is undefined

Hey there, I'm currently working on setting up environmental variables in my react app. Starting from scratch using webpack 4 and babel. Once I added the dotenv-webpack plugin to my webpack.config file, I encountered this error: TypeError: Cannot read ...

Display a div element for a specified amount of time every certain number of minutes

I am currently utilizing AngularJS, so whether the solution involves AngularJS or pure JS does not make a difference. In the case of using AngularJS, I have a parameter named isShowDiv which will determine the switching between two divs based on the follow ...

What is the best way to incorporate both a view and a partial view into an MVC project using JavaScript?

I am facing an issue where the order of actions being performed in my code is not as desired. I am trying to refresh the entire page after an ajax call completes a specific action, followed by loading a particular partial view. Here is my current attempt: ...

Navigating with NestJs without utilizing response usage

Can a redirect be initiated from a Nest controller without involving the use of the @Response object? Currently, the only method I'm aware of is through direct injection of the @Response object into the route handler. ...

Having trouble getting PostCSS nesting to work with CSS variables in Tailwind CSS and Next.js?

I've been attempting to utilize PostCSS nesting alongside CSS variables, but unfortunately the CSS variables are not being converted at all. Instead, I am seeing Invalid property value in the DOM for CSS Variables. The tailwind.css file I have inclu ...

Removing data using axios in a React project

I'm currently working on a small app using the Json server package to help me keep track of movies I want to watch in my free time. I am looking to learn React and Axios, so I decided to build this app with these technologies. The concept is simple - ...

Having trouble getting my HTML file and CSS styles to render properly in Chrome

Currently, I am in the process of developing a website and facing challenges with displaying CSS properties accurately. Despite seeking input from friends and users, my HTML file is not rendering as expected within various browsers such as Chrome, Edge, an ...

The webpack vue-loader throws an error message stating "unexpected token {" when processing a single-page .vue component

As a C# backend developer, I am venturing into the world of Vue.js. I typically work with Visual Studio 2017 + ASP.NET MVC (using it as an API + one layout) + Vue.js + Webpack. .vue single-page component files are loaded by vue-loader, while .js files a ...

Tips for maintaining variable values when invoking PHP functions

After setting a global variable value in a PHP functions file and successfully using it within one PHP file, I encountered an issue when trying to access the same variable from another PHP file using include("functions.php"). This is the process I followe ...

Obtaining Data from Fetch Response Instance

Currently, I am utilizing the fetch method to execute API requests. While everything is functioning as expected, I have encountered a challenge with one specific API call due to the fact that it returns a string instead of an object. Normally, the API pro ...