alittlecurryhot
alittlecurryhot

Reputation: 487

Deleting on a canvas

Im trying to create and delete arcs on events, to adding parts works fine and i'm saving them in arrays so i could delete them on calling an event listener by somehow that's not happening , I mean its working fine in the console as in the array values are decremented by its not updating in the canvas Code:

   <script>
    var myCanvas = document.getElementById("myCanvas");
    myCanvas.width = window.innerWidth;
    myCanvas.height = 500;
    var c = myCanvas.getContext("2d");
    var myArr = [];

    myCanvas.addEventListener("click", function(){    
        var x = event.x;
        var y = event.y;
        var radius = 10;
        myArr.push(new CreateCircle(x, y, radius, "#34495e"));
        console.log( myArr );

    });

    window.addEventListener('keydown', function(){
        myArr.splice(0,1);
        console.log(myArr);
    });

    function CreateCircle(x, y, radius, color) {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.color = color;

        this.draw = function() {
            c.beginPath();
            c.arc(this.x, this.y, this.radius, 0, Math.PI*2);
            c.fillStyle = this.color;
            c.fill();
        }
        this.draw();
    }


</script>

Do i need to add an delete function in the constructor function and call it on keydown event , how do i go on doing it/fixing it ?

Upvotes: 0

Views: 85

Answers (2)

adeneo
adeneo

Reputation: 318182

To remove the circles, you have to clear the canvas, and then redraw it with the modified array of circles.

First of all, return an object from the CreateCircle method, so you have something to work with. There's no need for instances here.

Secondly, you could clear the canvas by resetting it's width, and then redraw based on the array, like this

var myCanvas = document.getElementById("myCanvas");
myCanvas.width = window.innerWidth;
myCanvas.height = 500;
var c = myCanvas.getContext("2d");
var myArr = [];

myCanvas.addEventListener("click", function() {
  var x = event.x;
  var y = event.y;
  var radius = 10;
  myArr.push(CreateCircle(x, y, radius, "#34495e"));
});

window.addEventListener('keydown', function() {
  myArr.splice(0, 1);
  myCanvas.width = myCanvas.width;
  myArr.forEach(function(circle) {
    CreateCircle(circle.x, circle.y, circle.r, circle.c)
  })
});

function CreateCircle(x, y, radius, color) {
  c.beginPath();
  c.arc(x, y, radius, 0, Math.PI * 2);
  c.fillStyle = color;
  c.fill();

  return {x: x, y: y, r: radius, c: color};
}
<canvas id="myCanvas"></canvas>

Upvotes: 1

Michael Kurowski
Michael Kurowski

Reputation: 190

You don't update canvas anywhere. You need to create some sort of "render" function which will clear previously rendered frame and then loops through circles in array and call .draw on all of them.

Tip: context.clearRect method is useful for clearing canvas.

Upvotes: 1

Related Questions