Permanently removing artwork from the Canvas

I am facing an issue with my canvas drawing function. Whenever I clear the drawings on the background image by clicking a button, the old drawings reappear when I try to draw again. How can I permanently delete the cleared drawings so that I can start fresh without having to reload the page?

'use strict';

function initCanvas() {
let bMouseIsDown = false;
let canvas = document.getElementById('cvs');
let ctx = canvas.getContext('2d');
let convert = document.getElementById('convert');
let sel = 'png';
let imgs = document.getElementById('imgs');
let imgW = 300;
let imgH = 200;

let background = new Image();
background.crossOrigin = '';
background.src = "http://i.imgur.com/yf6d9SX.jpg";

background.onload = function(){
     ctx.drawImage(background,0,0,600,400);
}
bind(canvas,ctx,convert,sel,imgs,imgW,imgH,bMouseIsDown);
};

initCanvas()


function bind (canvas,ctx,convert,sel,imgs,imgW,imgH,bMouseIsDown) {
    let iLastX = 0;
    let iLastY = 0;
    let iX;
    let iY;
    canvas.onmousedown = function(e) {
        bMouseIsDown = true;
        iLastX = e.clientX - canvas.offsetLeft +         (window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft);
        iLastY = e.clientY - canvas.offsetTop + (window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop);
    }
    canvas.onmouseup = function() {
        bMouseIsDown = false;
        iLastX = -1;
        iLastY = -1;
    }
    canvas.onmousemove = function(e) {
        if (bMouseIsDown) {
            iX = e.clientX - canvas.offsetLeft + (window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft);
            iY = e.clientY - canvas.offsetTop + (window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop);
            ctx.moveTo(iLastX, iLastY);
            ctx.lineTo(iX, iY);
            ctx.stroke();
            ctx.strokeStyle = "blue";
            ctx.lineJoin = "round";
            ctx.lineWidth = 5;
            iLastX = iX;
            iLastY = iY;
        }
    };

    document.getElementById('clear').addEventListener('click', function() {
        rerenderImg();
    });
    
    function rerenderImg() {
        iY = [];
        iX=[];
        initCanvas()
    }
};

Answer №1

Make sure to invoke ctx.beginPath(); prior to starting any drawing on the canvas once more. The ideal location for this command is right before you use ctx.moveTo.

To understand why this step is necessary, check out the explanation provided here.

Answer №2

The appropriate action to take is to execute the clearRect function on the canvas:

ctx.clearRect(0, 0, canvas.width, canvas.height);

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

Utilizing NestJS to pass multiple IDs as parameters in an API

I am working with nestjs for the first time and I've been tasked with creating an API at http://localhost:8000/companies/4/5/8…. Does anyone know how to create this API using the GET(':id') method that can handle multiple parameters? ...

Prevent Button Click in ASP.NET After Validating Regular Expression in Textbox

How can I ensure that the asp button is disabled only after the user submits the form with the correct regular expression? Below is the form code: <asp:TextBox ID="TextBox2" runat="server" placeholder="Email" class="form-control" type="email" Font-Siz ...

Learn how to dynamically change a class name with JavaScript to alter the color of a navbar icon

I have little experience with javascript, but I want to make a change to my navbar icon. Currently, my navbar has a black background with a white navbar icon. As I scroll the page, the navbar background changes to white and the font color changes to black. ...

combine multiple select options values in a single function using jQuery

My HTML code includes two select options for users to choose the origin and destination cities. I need to calculate the cost of travel between these cities. How can I compare the selected options using jQuery? </head> <body> <div> ...

now.js - There is no method in Object, however the click event works in jQuery

Here is a simple NowJS code snippet for the client side: $j(document).ready(function() { window.now = nowInitialize('http://xxx.yyy:6564'); now.recvMsg = function(message){ $j("body").append("<br>" + message); } $ ...

Managing time in an Angular application using Typescript

I am facing an issue with formatting the time obtained from an API in my FormArray. The time is received in the format: 14.21.00 My goal is to convert this time to the following format: 2:21 PM I have attempted to format it using Angular's DatePip ...

The issue with ui-router failing to render the template in MVC5

I'm having trouble setting up a basic Angular UI-Router configuration. My goal right now is to have a hardcoded template render properly, and then work on loading an external .html file. My project is using MVC5, so I'll provide the necessary fi ...

[Vue alert]: Issue in created function: "TypeError: Unable to assign value to undefined property"

I'm currently in the process of developing a VueJS application where I have implemented a child component called Child.vue that receives data from its parent. Child.vue export default{ props:['info'], data: function(){ ...

Can you define the "tab location" in an HTML document using React?

Consider this component I have: https://i.stack.imgur.com/rAeHZ.png React.createClass({ getInitialState: function() { return {pg: 0}; }, nextPage: function(){ this.setState({ pg: this.state.pg+1} ) }, rend ...

Execute asynchronous functions without pausing the thread using the await keyword

When working with an express route, I need to track a user's database access without: waiting for the process to complete before executing the user's task worrying about whether the logging operation was successful or not I'm uncertain if ...

Utilize React JS to parse and display a sophisticated JSON structure in a dropdown menu

Looking at the backend data structure provided, we have information on various courses in different departments. { "courseDetails" : [{"departmentId" : 105654, "courses" : [{"stream" : "science","courseIds" : ["104","105 ...

Avoiding the insertion of duplicates in Angular 2 with Observables

My current issue involves a growing array each time I submit a post. It seems like the problem lies within the second observable where the user object gets updated with a new timestamp after each post submission. I have attempted to prevent duplicate entr ...

What is the best way to run tests on this asynchronous function using Jasmine?

My role in the service is listo: function () { var promiseResolved = $q.defer(); setTimeout(function () { promiseResolved.resolve(true); }, 2000); return promiseResolved.promise; } During my testing ...

Imitate a HTTP request

Currently, I am working on developing a front-end application using Angular (although not crucial to this question). I have a service set up that currently supplies hard-coded JSON data. import { Injectable } from '@angular/core'; import { Obser ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

Angular button press

Recently, I started learning Angular and came across a challenge that I need help with. Here is the scenario: <button *ngIf="entryControlEnabled && !gateOpen" class="bottomButton red" (click)="openGate()">Open</button> <button *ngIf ...

Sharing state between components in NextJS involves using techniques like Context API, passing

I am trying to pass state between pages in Next.js. In my App.js, I have wrapped it in a context provider like this: import { useRouter } from 'next/router' import { ClickProvider } from '../context/clickContext' function MyApp({ Compo ...

Utilizing square brackets in Node.js for working with URLs

While working in express.js, I encountered an issue when trying to add a router for the URL /xxx/xxx/items[5] that contains square brackets. The router functions correctly without square brackets but fails to work when they are included in the URL. Has a ...

Using Typescript and webpack to detect variables that are defined in the browser but not in Node environment

My goal is to create a package that can be used on both servers and clients with minimal modifications required. Some libraries are available in Node but not in a browser, while others are accessible in a browser but not in Node. For instance, when utili ...

Position the buttons in the react children's application

**Looking for help on positioning Black Widow in the center-left and Hulk at the bottom left of the screen. I'm having trouble figuring it out, does anyone have any tips? Also, I only want to isolate the buttons to each picture. Not sure if I need to ...