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

The information about the property is not appearing on the screen

I included the following CSS: nav label:AFTER { content: " ▾"; } However, when viewed in Chrome, it appears like this: content: " â–¾"; I have already added <meta charset="utf-8"/> to my JSP page and @CHARSET "utf-8"; in my CSS file. ...

Tips for creating CSS from the Google Chrome inspector for future use

Hey there, I spent the evening debugging my JSF page and noticed some changes in appearance when checking/unchecking options in Google Chrome Inspector. I want to create a new CSS file based on these checked options and save it for use in my web applicat ...

Optimizing the Placement of Dynamic Google Maps

After setting up a responsive Google map using this jsFiddle and guidance from this stack overflow post, I encountered an issue. How can I keep the map centered on the marker across various viewports and browser sizes? I came across a solution in this res ...

Can we pause and resume the progress bar using Javascript in conjunction with animationPlayState?

Looking for a way to control a progress bar script that runs for 180 seconds and then redirects the browser? Check out the code snippet below. I've added an onclick event to test pausing the progress bar. My goal is to pause, reset, and adjust the dur ...

iOS Chrome: Enabling Cookies with "Always Allow"

While the Safari browser on OSX has a setting under Privacy & Security -> Block Cookies -> Always Allow, enabling the storage of entries in the browser's local storage even when accessing pages from third party sites like those running in an iframe, I ...

What strategy should be employed to ensure that Javascript is operational upon completion of page loading?

I'm facing a challenge with running my JavaScript on my ASP.NET webform page. It seems like the elements are not fully loaded when the script runs, which could be causing issues. How can I use jQuery to ensure that my script is placed at the bottom of ...

What is the best way to continue looping until my variable matches the user's input? JavaScript

As of now, this nested for loop continues until both i and j reach 3. How can I reset the variables once they have reached their maximum value so that the loop can continue running? Alternatively, is my current approach incorrect? for (i=1; i<=3; i=i+ ...

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...

You won't be able to view over 15 KML layers on a page that relies on Google Maps API

I've encountered an unusual issue: I need to create multiple KML layers from separate KML files and display them on a single map window. The number of files ranges from just a couple to less than fifty. Currently, my code works perfectly when given 1, ...

Are we looking at a declaration of an arrow function? Is this concept even real?

I have been exploring the concept of function expressions versus function declarations with arrow functions. From my understanding, this is an example of an arrow function expression: const fred = greeting = () => { console.log("Hello from arrow ...

center the view on the specified element

Utilizing ReactJs, I am developing a horizontal timeline that showcases dates. For instance, there is a list of 100 elements, each containing a date and text content. The dates are displayed horizontally using flex-direction="row" and overflowX ...

The marriage of a sticky and floating navigation bar using the power of Bootstrap 4

I am currently designing a navigation bar inspired by the layout on the EA GAMES website. While it functions perfectly in Chrome, I am encountering significant display issues in Internet Explorer. Any suggestions on how to troubleshoot and resolve this pro ...

JavaScript code that functions similarly to VLOOKUP, allowing you to map input values from one field to

As a beginner in HTML and JavaScript, I am trying to create a simple form that automatically populates a specific "Customer Code" when a "Customer Name" is selected from a dropdown list (similar to an Excel VLOOKUP). However, the examples I found on Stack ...

Merge JSON objects while retaining duplicate keys

I am looking to merge two arrays containing JSON objects while retaining duplicate keys by adding a prefix to the keys. In this specific scenario, the data from 'json2' is replacing the data from 'json1' due to having identical keys, bu ...

How to customize the appearance of an element within a shadow DOM

I am currently implementing a custom CSS style over an application without the ability to modify its code. Initially, the DOM structure looked like this: <div class="foo"> <div class="bar"></div> </div> and I ...

Sequence of HTML elements arranged in a stack

Recently, I came across a useful jQuery tutorial called "jQuery for Absolute Beginners: Day 8". In this tutorial, there is an interesting code snippet that caught my attention: $(function() { $('.wrap').hover(function() { $(this).childre ...

The style of MUI Cards is not displaying properly

I've imported the Card component from MUI, but it seems to lack any styling. import * as React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/m ...

What is the best way to create a <div> that will automatically start a new line based on the user's input?

Is it possible to create a div that automatically inserts a new line for each new line in the code it detects when typing? For example, if I type: <div> Hello, World! How are you doing today? </div> This would normally be displayed as ...

Listen to music on an Android device without disturbing anyone using an iPhone

I have an application built in Vue3 that plays a sound when a QR code is scanned. This feature works perfectly on Android and the web, but not when using the browser on iOS. I am struggling to identify the issue. Can anyone provide some insight? <qrco ...

Can JSON be parsed using JavaScript?

Is it feasible to utilize JavaScript to parse information from an external URL hosting a JSON file on a different domain? The JSON data sample below shows various URLs with associated "q" values that I am interested in extracting. [{"url":"http://websit ...