mattdesl / canvas-sketch

[beta] A framework for making generative artwork in JavaScript and the browser.
MIT License
5.02k stars 393 forks source link

Placing two canvas elements on top of each other #186

Closed alexalex25 closed 7 months ago

alexalex25 commented 1 year ago

I have tried to put them in { display: block; } but no luck :

Screen Shot 2023-07-12 at 12 33 57 AM

mattdesl commented 1 year ago

A potentially simpler way would be to create a second canvas within the first sketch.


const sketch = ({ canvasWidth, canvasHeight }) => {
  const canvas2 = document.createElement('canvas');
  canvas2.width = canvasWidth;
  canvas2.height = canvasHeight;
  const context2 = canvas2.getContext('2d');
  return ({ context, width, height, scaleX, scaleY }) => {
    context2.save();
    context2.scale(scaleX, scaleY);
    /* draw to context2 */
    context2.restore();

    context.drawImage(canvas2, 0, 0, width, height);
  };
}

Just to note, this doesn't handle resizing (if you are running your sketch full-screen).

Another option is to use the code you've got, but use the { styleCanvas: false } setting so that you then apply styles manually to each canvas and have them position: absolute; in CSS.

alexalex25 commented 1 year ago

Thx ! :)