Guide to implementing a slider in HTML to adjust the size of my canvas brush

Hey there, I'm looking to implement a slider functionality under my canvas that would allow users to change the brush size. Unfortunately, all my attempts so far have been unsuccessful. Can anyone lend a hand? Much appreciated!

        <canvas id="myCanvas" width="800px" height="500px" style="border: 3px solid black"></canvas><br>
        <input type="range" id="vol" name="vol" min="0" max="100">
    
        <script>
          var c = document.getElementById("myCanvas");
          var ctx = c.getContext("2d");

          var xPos = 0;
          var yPos = 0;
          c.addEventListener("mousedown", setPosition);
          c.addEventListener("mousemove", draw);

          function setPosition(e) {
            xPos = e.clientX;
            yPos = e.clientY;
          }

          function draw(e) {
            if (e.buttons == 1) {
              ctx.beginPath();

              ctx.lineWidth = 5;
              ctx.lineCap = "round";
              ctx.strokeStyle = "#ff0000";

              ctx.moveTo(xPos, yPos);
              setPosition(e);
              ctx.lineTo(xPos, yPos);

              ctx.stroke();
            }
          }

          function clearScreen ()
          {
            var m = confirm("Do you want to clear your drawing?");
          }
            
        </script>

Answer №1

To implement functionality with the slider, you can add an event listener for the change event on the slider element.

<input id="slider" type="range" id="vol" name="vol" min="0" max="100"> // provide an id

// Start by setting up the slider variable and capturing its value 
var slider = document.querySelector("#slider");
var brushThickness = slider.value;
slider.addEventListener("change", (e) => brushThickness = e.target.value);

//continue onwards...

Then, in the draw function, set ctx.lineWidth to match brush thickness like this:

ctx.lineWidth = brushThickness;
 

For a live demonstration of these changes, click here.

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

The function body.getReader() doesn't seem to be functioning properly on Ubuntu

I am currently in the process of deploying a project on Ubuntu Server 22.04. The tech stack I am using is Next.js + Nest.js. I have come across an issue where my Fetch API behaves differently - on my localhost (macOS) everything works smoothly and I rece ...

Could someone help clarify this issue within a React project?

I've encountered an issue with a react task and I could use some clarification. // React is loaded and is available as React and ReactDOM // imports should NOT be used class Input extends React.PureComponent { render() { let {forwardedRef, ...ot ...

Enhance Fullcalendar by incorporating an HTML tag alongside the "titleformat" option

I am utilizing the jQuery Fullcalendar agenda feature. My main objective is to link an action with each date that appears in the calendar and enable the opening of a separate window for each date. Therefore, I am looking to include a button or a link next ...

Placing an Image in the Right Corner Using jQuery Mobile

I am currently developing a mobile app and I need to align three images one below the other at the right corner next to some text. Any suggestions would be greatly appreciated. Thank you in advance. Below is my code snippet: <div> <ul data-r ...

Implement functionality in JS to track the number of clicks on an element

I am dealing with a ul-list containing an unpredictable number of li-elements, ranging from 2 to 8. My goal is to capture votes using these li-elements and display the vote count on the specific element that was clicked. I have attempted to catch the click ...

What is the best way to convert an object array into an array with identifiers for duplicate values?

Working with the following array of objects: const data = [ {count: 400, value: "Car Wash Drops"}, {count: 48, value: "Personal/Seeding"}, {count: 48, value: "Personal/Seeding"}, ]; I want to use the map function to create an array with an addition ...

The useLocation state is returning as null

I've encountered a debugging issue with my app. It's a straightforward application that fetches random API images from Spoonacular, allowing users to either select "Yah" or "Nah" similar to Tinder. Upon choosing "Yah", the image should be added t ...

When implementing javascript_pack_tag in Rails, an EOFError may occur

It seems like the files in public/packs/js are having trouble loading. Here are the javascript tags being used in the view: = javascript_include_tag 'application' = javascript_pack_tag 'application' The error displayed in the browser ...

Can a rotationX be applied within an existing rotationX?

I have a collection of 3 divs labeled a, b and c inside a container. The container is rotatedX by 90 degrees, giving the appearance that it is "lying on its back". Now, I am trying to rotate the a, b, and c divs so they appear to be "standing up" again. Ho ...

Javascript - Issue with Ajax causing additional commas in JSON responses

I'm attempting to send a request to a RESTful server using the HTTP module in Node.js. Due to the large response size (64 chunks, approximately 100kb), the HTTP module combines the chunks into a single string response like this: res.setEncoding(& ...

Revisiting a jQuery ajax call using the response text

I have been attempting to implement ajax in the following way; Here is the jQuery code I am using: $("a.generate").click(function(){ $.ajax({ data: {tag: $(this).html()}, success: function(data){ $("#terms div.content").ht ...

Design a dynamic table using JavaScript

After spending hours working on my first JavaScript code, following the instructions in my textbook, I still can't get the table to display on my webpage. The id="eventList" is already included in my HTML and I've shortened the arrays. Here' ...

How do three buttons display identical content?

I have three buttons on my website, each with its own unique content that should display in a modal when clicked. However, I am experiencing an issue where regardless of which button I click, the same content from the last button added is displayed in the ...

Once the vue-cli has deployed to the server, the server's requested image path is now located in /dist/ folder

Issue with Image Loading: While the demo successfully loads all resources and uploads images correctly, there is an issue where an extra /dist/ is being requested for image paths, resulting in a 404 error. Demo Link: Configuration of the Demo: vue.conf ...

"Revolutionize Your Site with Endless Scrolling using q

I am currently in the process of developing a web application using create-react-app along with the packages Infinite-Scroller and qwest. (https://www.npmjs.com/package/react-infinite-scroller) (https://www.npmjs.com/package/qwest) This is how my code l ...

Insert image using AJAX

I am attempting to use Ajax to dynamically add an <img> element to a div on my webpage. The image's name needs to be fetched from a database. Although I have successfully added the <img> tag to the div and set the correct source (src) att ...

Adjust tool tip text on the fly

As a beginner, I created a test table and now I want to make the tool tip text change dynamically when I hover over the table with my mouse. Ideally, I would like the tool tip text to correspond to the content of the table cell. Currently, I only have stat ...

Emulating a form submission using a jQuery AJAX request

I am working with a block of code that defines div elements as well as their click callbacks. In order to prevent repetition in my code, I am looking to reuse it. Currently, the callbacks are utilizing $.post calls to interact with the server, but on this ...

jQuery does not have the capability to access the href attribute through DOM manipulation

I've been trying to extract the href attribute from a link in my code and create a new link using that attribute. However, I'm facing an issue where the created link doesn't seem to work properly - it keeps showing a 404 error message like t ...

Ways to ensure the height of an element is consistent across various device modes

Testing out the angular-youtube-embed plugin with Chrome Dev tools' device mode, I wanted to see how the YouTube element would appear. Here's my code: <div class="fixed-header my-video"> <div style="padding:0px;"> <yo ...