Skip to content
Advertisement

Redraw Canvas via p5 with deleting the old canvas

I want to visualize my sorting algorithms and redraw the created Canvas each time. My Old Canvas keeps all the old values. It just creates a new Canvas and puts it above the old Canvas. But I thought with the redraw I could solve it. I also tried to delete the canvas via canvas.remove() and create a completly new one and it also didn’t worked out.

My setup call:

let canvas;

function setup() {
  values = new Array(20);
  this.canvas = createCanvas(values.length*w, 640);
  createArray(values.length);
  var slider = document.getElementById("slider");
  slider.oninput = function() {
    this.canvas = resizeCanvas(values.length*w, 640);
    length = this.value;
    createArray(length);
    redraw();
  }
  var button = document.getElementById("btn");
    button.onclick = function(){ 
        quickSort(values, 0, values.length - 1);
  }
  
}

And my draw call:

function draw() {
  background(0);
  for (let i = 0; i < values.length; i++) {
    noStroke();
    if (states[i] == 0) {
      fill('#E0777D');
    } else if (states[i] == 1) {
      fill('#D6FFB7');
    } else {
      fill(255);
    }
    rect(i * w, height - values[i], w, values[i]);
  }
}

Thanks for helping me out :).

Advertisement

Answer

Try to do canvas=null when you are done using the canvas

Advertisement