Having trouble drawing over buttons in HTML5 Canvas?

window.addEventListener("load", () => {
    const canvas = document.querySelector("#canvas");
    const ctx = canvas.getContext("2d");
    const color = document.querySelector("#color");
    const strokeWeight = document.querySelector("#strokeWeight");
    const eraser = document.querySelector('#eraser');
    
    //variables
    const clearButton = document.querySelector("#clear");

    let painting = false;

    function startPosition(e) {
      painting = true;
      draw(e);
    }
    function finishedPosition() {
      painting = false;
      ctx.beginPath();
    }

    function draw(e) {
      if(e.which == 1) {
        ctx.lineCap = "round";
        ctx.lineTo(e.clientX, e.clientY);
        ctx.stroke();
        ctx.beginPath();
        ctx.moveTo(e.clientX, e.clientY);
      } else {
      finishedPosition();
      }

    }

    function changeColor(e) {
      const color = e.target.value;
      ctx.strokeStyle = color;
    }

    function changeStrokeWeight(e) {
        const strokeWeight = e.target.value;
        ctx.lineWidth = strokeWeight;
    }

    function clickEraser() {
        ctx.strokeStyle = 'white';
    }


    //Event listeners
    canvas.addEventListener("mousedown", startPosition);
    canvas.addEventListener("mouseup", finishedPosition);
    canvas.addEventListener("mousemove", draw);

    color.addEventListener("input", changeColor);
    strokeWeight.addEventListener("input", changeStrokeWeight);
    eraser.addEventListener("click", clickEraser);
    //Buttons
    clearButton.addEventListener("click", clearCanvas);

    function clearCanvas() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
});

window.addEventListener("resize", resizeCanvas);
function resizeCanvas() {
    //Resizing
    canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;
}
resizeCanvas();
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

#canvas {
    border: 0.0001px solid white;
}

html {
    overflow: hidden;
}

#clear {
    position: absolute;
    top: 0;
    left: 0;
  
  .
  . Add your unique additional content here.
  .

</section>
  </body>
</html>

Whenever I draw and hover over the buttons, I can draw over the buttons but I don't want that. With the clear button and eraser button when I increase the thickness I can draw over the buttons. Is there anything to stop this from occurring. Is there any border I can add around the button or anything that doesn't show on the canvas but blocks this from happening.

Answer №1

you just forgot && painting when

function draw(e) {   // drawing
  if (e.which == 1 && painting) {

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

Nuxt Page Featuring One Exclusive Product

I am just getting started with Nuxt and I'm in the process of creating a Single Product. I have some questions: How can I generate multiple pages using SSR and create a unique HTML for each page? Should CSR be developed first before implementing SSR, ...

Show image details on hover?

I have six images displayed full width using a flex grid. I would like the image information (along with a visit button) to appear on hover, and the brightness of the image should decrease. I am struggling to position the information in the center of the i ...

Displaying specific choices depending on the previous selection made

I am facing an issue in Laravel where I have two selection options, and one depends on the other. Despite multiple attempts, I haven't been able to resolve it. The database structure is as follows: companies id title channels id company_id title I ...

Ways to insert data in angularjs

As I attempt to add data to a list using the addGroup function, I encounter a type-error. The error message reads: "TypeError: Cannot read property 'push' of undefined" at r.$scope.addGroup (main.js:7) at fn (eval at compile (angular ...

Does width change based on position?

When I set position:absolute for an element, its width remains constant regardless of the text inside. However, if I set position:relative for the same element, the width will adjust based on the text content. I have created a fiddle with two menus, each ...

Update the state within a different function in Vue.js

Just starting out with Vue.js and I'm trying to figure out how to update the component's state from a function in another file. I have a basic form with only an input file element. Once the user selects a file, the onChange handler will be trigg ...

What could be the reason behind getting a useLayoutEffect error when using renderToString to render a Material-UI component?

Currently, I am utilizing React version 16.12.0 along with @MaterialUI/core version 4.8.1. The challenge I am facing involves creating a custom icon for a React Leaflet Marker. The icon in question is a Fab component sourced from Material-UI. In order to ...

Is it advisable to employ jQuery(this) in this specific scenario?

My PHP script generates HTML a:link divs with different $linkname and $pageid values. It also creates corresponding jQuery scripts for each link: $output = '<a class="sig_lightbox_link" id="' . $pageid . '">' . ...

The array does not seem to be properly linked in React JS

I've been encountering this error even after trying various solutions based on my knowledge. Any help would be greatly appreciated. The issue arises when I attempt to pass an array in props, retrieve it in the component, and then set the props value ...

Looking for an Angular Material component that displays a list of attributes?

I am trying to create a dynamic list of properties in Angular using Material Design that adjusts for different screen sizes. For example, something similar to this design: https://i.stack.imgur.com/EUsmV.png If the screen size decreases, the labels shou ...

Switch classes while navigating within a div

My website has a sticky sidebar with a list of cars and their corresponding categories in a table: <ul class = "cars"> <li class=""><a href="javascript:void(0)" class="model" data-id="1"> BMW </a></li> ...... ...

The functionality of the "Slots" prop has no impact when used on the material-ui Slider component

Trying to understand the purpose of the "slots" prop in relation to customizing how inner components like track and thumb are rendered within the Slider component. A basic example of rendering a Slider component is shown below const marks = [ { value: 0 ...

What is the purpose of using overflow:hidden; in our code?

I am curious about the rationale behind using these three properties on this menu. I don't quite understand why they are necessary. I am eager to delve into the technical reasoning behind this. margin: 0; padding: 0; overflow: hidden; Snippet of HTM ...

An error occurs when trying to modify the classList, resulting in an Uncaught TypeError for setting an indexed property

I am attempting to modify the classes of multiple sibling elements when a click event occurs. Some of these elements may have multiple classes, but I always want to change the first class. Below is the code that I created: let classList = event.currentTa ...

How to integrate a jQuery plug-in into your Meteor 1.7.0.3 project

Recently, I delved into using Meteor for the first time, and it has been about a week since I started exploring its functionalities. However, I encountered an issue with integrating jQuery plugins that were installed via npm. After running: meteor npm i ...

While attempting to run the project I downloaded from GitHub using the command npm run serve, I encountered the following error: "Syntax Error: Error: No ESLint configuration found in

After receiving a Vue.js project from GitHub, I attempted to download and run it. However, when I tried the command npm run serve, I encountered an error message: Syntax Error: Error: No ESLint configuration found in C:\Users\User\Desktop&bs ...

What is the reason that asynchronous function calls to setState are not grouped together?

While I grasp the fact that setState calls are batched within react event handlers for performance reasons, what confuses me is why they are not batched for setState calls in asynchronous callbacks. For example, consider the code snippet below being used ...

To ensure proper functionality, make sure that Python Selenium's Geckodriver is correctly

I want to automate form filling using Selenium. Below is the HTML code for the form: <!DOCTYPE html> <html> <body> <h2>Text input fields</h2> <form> <label for="fname">First name:</label><br& ...

Prevent Overflow with Hidden Setting, Use Cover for Background Image, and Optimize for Anchors and

I'm currently working on a page that is designed not to scroll vertically. If you'd like to see the page with the issue I'm encountering for reference, you can visit Everything has been running smoothly except for two specific issues: W ...

Can TypeScript be used to dynamically render elements with props?

After extensive research on SO and the wider web, I'm struggling to find a solution. I have devised two components, Link and Button. In short, these act as wrappers for <a> and <button> elements with additional features like chevrons on t ...