user1879653 user1879653 - 5 months ago 18
Javascript Question

Erase canvas rectangle from a stack

I have this code:

var stack = new Array();
var last = 0;
var pospintar=0;

function Cuadrado(pcolor,pcostat){
this.color=pcolor;
this.costat=parseInt(pcostat);
}

function pintar(){
var canvas = document.getElementById('tutorial');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext){
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Draw shapes
//ctx.fillStyle="#ff0000";
var vCuadro=stack[last];
ctx.fillStyle=vCuadro.color;
var lado=vCuadro.costat;
ctx.fillRect(20,pospintar,lado,lado);
//ctx.strokeRect(20,posPintar,lado,lado);
}
}

function empilar(color,costat)
{
var vCuadro = new Cuadrado(color,costat);
stack[last]=vCuadro;
pintar();
var vCuadro=stack[last];
var lado=vCuadro.costat;
pospintar+=lado;
last+=1;
}
function desempilar()
{

}


The function
empilar
draws rectangles the same size as variable
costat
.

How can I make the opposite function,
desempilar
, erase the last rectangle drawn?

Answer

In pintar function you should clear the canvas, go through stack array and paint each square. And in desempilar function you need to remove the last element from stack and reduce last variable by 1 and call pintar again.

function pintar() {
    var canvas = document.getElementById('tutorial');
    if (canvas.getContext) {
        var ctx = canvas.getContext('2d');
        ctx.clearRect(0,0,canvas.width,canvas.height); // Clear canvas
        var pospintar = 0;
        for (i in stack) {
            var vCuadro=stack[i];
            ctx.fillStyle=vCuadro.color;
            var lado=vCuadro.costat;
            var pospintar += lado;
            ctx.fillRect(20,pospintar,lado,lado);
        }
   }
}

function desempilar() {
    stack.splice(last, 1);
    last--;
    pintar();
}
Comments