The YUI framework is skilled at creating new lines while erasing the old ones

I am looking to create a line when the mouse is clicked, and remove the previously drawn line. View the code on jsfiddle.net at this link.

While my current code successfully draws a line when the mouse is clicked, it does not remove the previous line. I need assistance with removing the previous line. Can someone help me? Thank you!

Here is the YUI code snippet:

YUI().use('event', 'node', 'graphics', function (Y) {
var mygraphic = new Y.Graphic({
    render: "#play"
});

Y.one('#play').on('click', function (e) {
    var bob = mygraphic.addShape({
        type: "path",
        stroke: {
            weight: 4,
            color: "#00dd00"
        },
        fill: {
            type: "linear",
            stops: [{
                color: "#cc0000",
                opacity: 1,
                offset: 0
            }, {
                color: "#00cc00",
                opacity: 0.3,
                offset: 0.8
            }]
        }
    });
    if (bob) {
        bob.moveTo(100, 100);
        bob.lineTo(e.clientX, e.clientY);
        bob.end();
        bob.closePath();
        //mygraphic.removeShape(bob);
    }
});

});

And here is the snippet for the HTML and CSS code:

<div id="play"></div>

#play {
    width:400px;
    height:300px;
    border:1px solid black;
}

Answer №1

To ensure that you can delete the previously drawn line upon subsequent clicks, it is essential to have a reference to it. I have made some enhancements to your code on jsfiddle, which you can view here: http://jsfiddle.net/q2v14w8s/5/. The key is to utilize a variable that is defined in the outer scope, specifically within the YUI.use() callback rather than the 'click' callback scope. This variable is set to bob, and the previously drawn line is stored in oldBob before being removed from the Graphic.

With these updates, your code now looks like this:

var mygraphic = new Y.Graphic({
        render: "#play"
    }),
    oldBob;

And in the event listener:

if (bob) {
    bob.moveTo(100, 100);
    bob.lineTo(e.clientX, e.clientY);
    bob.end();
    bob.closePath();

    if (oldBob) {
        mygraphic.removeShape(oldBob);
    }
    oldBob = bob;
}

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

Occasional Laravel Token Mismatch Issues

In my Laravel application, the token is displayed in a field on each page. This token is then loaded by jQuery into every ajax request, as explained in this answer: Laravel 5 CSRF global token hidden field for all forms in a page However, I occasionally e ...

A few of the input fields I filled out are not getting sent to the PHP script

Currently, I am working on a school project that involves creating a website similar to IMDB. My task is to include comments in our database, but I am facing an issue where two fields (fid and spoiler) are not getting posted to the PHP script handling the ...

Handling concurrent requests in DjangoDiscover how Django manages multiple simultaneous requests

Handling multiple requests in a web application can be a challenging task, especially when the server needs to perform complex operations like making API requests and executing database queries. In this post, we will explore how Django can effectively mana ...

Using FormData to send an image and string data with a Jquery POST request

In this particular section of code, jQuery is being used: $(".btnGorevOlustur").click(function (e) { var fileUpload = $(".fileGorevResim").get(0); var files = fileUpload.files; var dt = new FormD ...

Looking to display user data within a specific div using JavaScript? Check out my code!

Issue Solved by Me I resolved the problem by using ko.js to check data binding in java! Thanks to everyone who helped. I have implemented this code to display online users in my chat application (x7chat 3, available for free download) The code can be fou ...

JavaScript's XMLHttpRequest

My attempt to bypass the WebGoat prompt involved using a combination of javascript code with XMLHttpRequest to send multiple requests, one using GET and the other using POST. The code snippet is as follows: <script> var req1 = new XMLHttpRequest() ...

Why does my jQuery code target all the text values?

Looking to grab a specific table cell number and multiply it by an input value on focusout, but having trouble with the selector grabbing all cells with "front" in the name. Check out the code below: jquery $(document).ready(function(){ $(".percent") ...

Is it possible for an AJAX request to return both HTML data and execute callback functions simultaneously?

Is it possible to update the content of an HTML div and call a JavaScript function with specific parameters obtained through AJAX after the completion of the AJAX request, all within a single AJAX call? ...

What could be causing my dangerouslySetInnerHTML to show altered content?

I am working on a project using React and have encountered an issue with the code: const externalMarkup = ` <a data-refpt='DN_0OKF_177480_ID0EMPAC' /> <ol> <li value='1'> <p> <strong&g ...

Master the art of managing filenames with JavaScript

Here is a piece of javascript code that I created: fileName = "Report_" + Name + ".csv" var hiddenElement = document.createElement('a'); hiddenElement.href = 'data:attachment/text,' + encodeURI(data); hiddenElement.targ ...

Unable to display individual elements of an array using the map function in React Native

Below is my react-native code that I am using to display a list of array elements using the map function. import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import {Card} from 'react-native-e ...

Errors encountered by the Chrome extension

Hey there, I've recently delved into creating a chrome extension but hit a roadblock. My issue revolves around the service worker registration failing and encountering errors related to undefined properties. https://i.stack.imgur.com/bGzB4.png The c ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

Is it possible to prevent the late method from running during the execution of Promise.race()?

The following code snippet serves as a simple example. function pause(duration) { return new Promise(function (resolve) { setTimeout(resolve, duration); }).then((e) => { console.log(`Pause for ${duration}ms.`); return dur ...

Issue with Mongoose: Create operations are not functioning properly right after performing Delete operations

I need to refresh my collection by deleting all existing documents and then repopulating them with new data from an API call. But when I try running the delete operations first, no new documents are created. Below is a simplified version of my controller ...

What could be causing the misalignment of the Datepicker calendar in Material UI?

I have integrated a datepicker using the library "@mui/x-date-pickers/DatePicker". import { DatePicker } from "@mui/x-date-pickers/DatePicker"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import { Locali ...

Communication between the register service worker and the client page begins with the dispatch of a

Looking to pass a boolean variable to app.js when the registration onupdatefound function is triggered. This way, whenever a new update is received, app.js will be notified and I can display a popup with a refresh button. I have most of it implemented alr ...

retrieving identifiers from a separate table for an array of values

As a newcomer to node and noSQL databases, I am facing challenges in grasping the concept of passing an array of IDs and retrieving the corresponding values from another table. I have 'users' and 'products' tables in my database. The st ...

refresh-free form clearing

Currently, I am working on a form that includes Recaptcha validation using jQuery. The form is functioning well as the information is sent to my email and all required fields are checked before submission. However, there is one issue that I am encounterin ...

Tips on restricting users to choose dates that are later than the current date

Currently, I am working with Vue3 using the options API. After reviewing this StackBlitz, my question is regarding how to correctly set the :max value for a date-picker. Even though I have assigned :max as new Date(), I am still able to select dates that ...