1

Following instructions from this question, I have a div which is being cloned that has a p5 canvas inside it. When it is cloned the canvas is not responsive to mouse coordinates.

How do I make the p5 canvas still active after cloning?

$(document).ready(function() {
  $(".showcanvas").click(function() {       
    // Find the original canvas element
    var origCanvas = $(".canvas").first().find('canvas')[0];

    // Clone the div wrapper
    var clonedDiv = $(".canvas").first().clone(true);

    // Find the cloned canvas
    var clonedCanvas = clonedDiv.find('canvas');

    // Update the ID. (IDs should be unique in the document)
    clonedCanvas.prop('id', 'defaultCanvas' + $(".canvas").length)

    // Draw the original canvas to the cloned canvas
    clonedCanvas[0].getContext('2d').drawImage(origCanvas, 0, 0);

    // Append the cloned elements
    clonedDiv.appendTo("article").fadeIn('1200');
  });
});

https://jsfiddle.net/vanderhurk/12fxj48h/28/

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

0

I was going to comment on your previous question about this. The approach you're taking of cloning the canvas element and then drawing the old canvas into the new canvas is going to have exactly this problem: the new canvas is not going to change as the old canvas changes. This might work if you just want to take a snapshot (although there are easier ways to do this), but my guess is it's not what you're looking for.

Instead of cloning the element and dealing with JQuery, I suggest you look into using instance mode from the P5.js library. You can read more about instance mode here, but basically it allows you to package your P5.js code in a self-contained object.

Here's a simple example:

var s = function( sketch ) {

  var x = 100; 
  var y = 100;

  sketch.setup = function() {
    sketch.createCanvas(200, 200);
  };

  sketch.draw = function() {
    sketch.background(0);
    sketch.fill(255);
    sketch.rect(x,y,50,50);
  };
};

var myp5 = new p5(s);

If I were you, I would encapsulate the creation of an instance-mode P5.js sketch into a function or class. Then whenever I want to create a new copy of the sketch, I'd call that function or class. You could also store any shared state in global variables that both sketches access.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • I am using instance mode. However I require the p5 canvas to be hidden and called upon within divs which are set up to clone... – Kelly van der Hurk Oct 22 '18 at 16:27
  • @KellyvanderHurk I'm not totally sure what that means, but instance mode should work fine for this. You shouldn't have to clone any elements yourself. I'd do something like create an element, set its ID, and then pass that ID into my instance mode sketch creator. – Kevin Workman Oct 22 '18 at 16:35