Click here to Skip to main content
15,891,976 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As title.
I'm maintaining a system. I got a request that when I click on a line in a canvas, the line color changes for some seconds and changes back to original color. I searched and find a way to solve it is to create a new canvas over the old canvas, draw a line with new color in it, and make it disappear after some seconds. I tried it but failed:
JavaScript
var newcanvas = document.createElement("canvas");
                newcanvas.id = "newcanvas";
                newcanvas.style.top= canvas.style.top;
                newcanvas.style.left = canvas.style.left;
                newcanvas.style.width = canvas.style.width;
                newcanvas.style.height = canvas.style.height;
                newcanvas.style.position = "absolute";
                newcanvas.style.display = "block";
                document.getElementsByTagName("body")[0].appendChild(newcanvas);
                //change color
                var ctx = newcanvas.getContext("2d");
                ctx.strokeStyle="#FFFF00";
                for (var r = 0; r < linePoints.length - 1; r += 1) {
                    ctx.moveTo(linePoints[r].x, linePoints[r].y);
                    ctx.lineTo(linePoints[r + 1].x, linePoints[r + 1].y);
                }
                ctx.stroke();
                //switch back in 4 seconds
                setTimeout(function () {
                    newcanvas = undefined;
                    runAnimation.value = false;
                }, 4000);

The new canvas appears at right side of the old canvas and is still there after 4 seconds. That isn't what I want. How could I make it?

What I have tried:

(code in my problem description)
Posted
Comments
enhzflep 3-Jan-19 20:41pm    
"newcanvas = undefined;" will cause the javascript variable to now be useless, but you still have to do something with the element on the page... Why not have it's parent remove it from the DOM?
Momoko Asahina 708H 3-Jan-19 21:57pm    
Eh....Sorry for bad English, but I need that canvas just for temporary use. When I need it, I just need to create it same way again.
And, I also tried another way to destroy it:
document.body.removeChild(document.getElementById("newcanvas"));

and it works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900