I want to draw a line when clicking the mouse, and remove the previous line. This is the link from jsfiddle.net and the link is there.
In my code, I realize that draw a line when clicking the mouse. But can not remove the previous line. I want to remove the previous line. Could someone helps me? Thanks a lot!
This is YUI code:
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);
}
});
});
This is html and css code:
<div id="play"></div>
#play {
width:400px;
height:300px;
border:1px solid black;
}
You need a reference to the previously drawn line so you can remove it on subsequent clicks. I've updated your jsfiddle here: http://jsfiddle.net/s9b67qc9/11/ but the idea is to use a variable defined in the outer scope (ie the scope of the YUI.use() callback, rather than the scope of the 'click' callback). This gets set to bob
, and oldBob
is then removed from the Graphic.
So now you have:
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;
}