Axeowny
Axeowny

Reputation: 21

How to store created canvas objects

I created a event that creates squares side to side for every click event on the canvas. But how can I store each square so that I can then later on for example delete the last square by pressing a square.

If it helpful this my function for created squares (I have then added an EventListener for the vent click on the canvas and then run the function). The click Value is just an object that I have created that stores the number of clicks on the canvas. Board is my canvas access variable.

var x =0, y = 3;
    var createSquares = function () {
            var yTimeslength = y * clickValue.length;
            if (yTimeslength<60 ) { 
                board.fillStyle = "orange";
        var square = board.fillRect (0,yTimeslength,y,y);

Upvotes: 0

Views: 887

Answers (2)

Anbarasan
Anbarasan

Reputation: 1207

you can store the clickValue based on which you draw the squares in an array.

var x =0, y = 3, clicks = [];
var createSquares = function () {
    var yTimeslength = y * clickValue.length;
    if (yTimeslength<60 ) { 
        board.fillStyle = "orange";
        var square = board.fillRect (0,yTimeslength,y,y);
        clicks.push(clickValue);
    }
}

So, all the squares you drew based on the clickValue will be available in clicks array.

So, as in your said, if you want to delete a square, then based on the user click pos, you will have to determine which clickValue corresponds to the click and then remove it from the clicks array, and redraw every square again.

i have created a fiddle with your description, hope it helps. you click on empty space, a square is drawn, if you click on a square the square is deleted.

http://jsfiddle.net/b9fssptk/4/

Upvotes: 1

stdob--
stdob--

Reputation: 29172

It is best to use ready-made engines with support for interactivity and the object model.

For example CreateJS or PIXI.JS or Fabric.js or other..

Upvotes: 0

Related Questions