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

How to design a trapezium shape using CSS and HTML

While there are many tutorials available for creating Trapezoids with CSS3, I am interested in making a four-sided shape where none of the sides are parallel (trapezium), similar to the one shown in the image below. Can this be achieved? ...

PHP or jQuery: What is the most effective approach for updating metatags?

My website features a dynamic slideshow of content powered by jQuery. Users simply click on an arrow to reveal the next hidden div containing relevant information. Each div, whether visible or not, contains hidden span tags with the title and summary of th ...

What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file. .js $scope.uploadFilename = function (files) { if (!files[0]) { return; } var reader = new FileReader(); reader ...

In order to showcase an image ahead of another (stay tuned),

Help! I'm facing a dilemma here. I have an abundance of adorable animal images with unique facial expressions, but there's one problem - the eyes are hidden! I desperately want to showcase those captivating eyes. This is what my code looks like. ...

JavaScript code is failing to render data properly within HTML documents

I am facing an issue while trying to display data extracted from JSON in HTML. Despite my efforts, the data is not showing up on the webpage. I am unsure about what might be causing this error. Any assistance in resolving this matter would be greatly appre ...

Removing invalid characters in a *ngFor loop eliminates any elements that do not meet the criteria

I am facing an issue with my *ngFor loop that is supposed to display a list of titles. fetchData = [{"title":"woman%20.gif"},{"title":"aman",},{"title":"jessica",},{"title":"rosh&quo ...

What is the best way to fit the text into a DIV row as efficiently as possible?

Looking for a solution to prevent a span from dropping down to the next line when text is too long within a fixed width and height row. The row consists of three elements, two with fixed widths and the third containing a span and text. Constraints include ...

Checking for an empty value with javascript: A step-by-step guide

Below is an HTML code snippet for checking for empty or null values in a text field: function myFormValidation() { alert("Hello"); var name = document.getElementById("name").value; alert(name); if (name == null || name == "") { document.ge ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

Verify whether the input field contains a value in order to change certain classes

My meteor-app includes an input field that dynamically changes position based on whether it contains content or not. When a user begins typing, with at least one character, the input field moves to the top of the page. In my current approach, I am using a ...

Error Alert: Vue is not recognized in Browserify environment

My venture into front-end development has just begun and I am experimenting with Vue.js along with Browserify. The main 'app.js' file includes: window.$ = window.jQuery = require('jquery'); require('bootstrap'); var moment = ...

What is the best way to extract content between <span> and the following <p> tag?

I am currently working on scraping information from a webpage using Selenium. I am looking to extract the id value (text) from the <span id='text'> tag, as well as extract the <p> element within the same div. This is what my attempt ...

When attempting to use the ResponsiveSlides plugin, the functionality of 'Image links' seems to be disabled in the Chrome browser

While everything is functioning perfectly in Firefox and IE, I've encountered an issue with Chrome. It only works after right-clicking and inspecting the element; once I close the Inspector, it stops working - displaying just an arrow cursor as if the ...

The width of an iframe cannot exceed the width of its jQuery dialog box container

Exploring a JavaScript issue: When I include an iframe in my dialog, the width of the iframe is only about half of the dialog's width. It appears that jQuery is overriding the width value I specify and setting it to 'auto' instead. <htm ...

Creating a 3D slider on Owl-carousel 2: A Step-by-Step Guide

I am trying to create a slider using Owl-carousel, but I'm having trouble implementing it. I came across this example https://codepen.io/Webevasion/pen/EPMGQe https://i.stack.imgur.com/KnnaN.jpg However, the code from this example doesn't seem ...

Ways to implement a filter pipe on a property within an array of objects with an unspecified value

Currently, I'm tackling a project in Angular 8 and my data consists of an array of objects with various values: let studentArray = [ { Name: 'Anu', Mark: 50, IsPassed: true }, { Name: 'Raj', Mark: 20, IsPassed: false }, { Na ...

How to use jQuery to set a background image using CSS

I've been working on setting backgrounds dynamically with a jQuery script, but it seems like the .css function is not working as expected. Here's the code snippet: $(document).ready(function () { $(".VociMenuSportG").each(function () { ...

Why is my HTML image stored in the database not showing up in TCPDF?

Currently, my situation involves using TCPDF to retrieve content from a MySQL table row that contains HTML code like this: <p><a href="x.html"><img src="http://1/2/3/x.jpg" width="x" height="x"></a></p> The problem arises wh ...

What is the best way to maintain the formatting of a textarea in the database?

My HTML form includes a text area and a functionality to save the data into a database upon submission. The issue arises when the saved data is retrieved from the database, as the original formatting of the text gets altered. For instance: "This is a text ...

Using jQuery to dynamically insert a table row with JSON data into dropdown menus

I'm working on a web form that includes a table where users can add rows. The first row of the table has dependent dropdowns populated with JSON data from an external file. Check out the code snippet below: // Function to add a new row $(function(){ ...