P5js Copy Text to Clipboard

From Digipool-Wiki
Revision as of 08:09, 8 June 2021 by WikiSysop (Talk | contribs)

Jump to: navigation, search

P5js Copy to Clipboard

P5js-Copy-Text-to-Clipboard.png

Leider gibt es keinen P5JS Befehl, mit dem sich der Text in die Zwischenablage kopieren lässt. Doch dieses Problem ist mit einer zusätzlichen Funktion leicht zu lösen.

Probiere es selbst aus! LINK


Um im umgekehrten Weg Text aus der Zwischenablage in einen P5JS Anwendung zu kopieren, könntest Du einen Textarea (LINK) verwenden.


Funktion

Füge diese Funktion in deinen Code ein, damit du den Befehl copyStringToClipboard(myString) benutzen kannst.


function copyStringToClipboard (str) {
   // Create new element
   var el = document.createElement('textarea');
   // Set value (string to be copied)
   el.value = str;
   // Set non-editable to avoid focus and move outside of view
   el.setAttribute('readonly', '');
   el.style = {position: 'absolute', left: '-9999px'};
   document.body.appendChild(el);
   // Select text inside element
   el.select();
   // Copy text to clipboard
   document.execCommand('copy');
   // Remove temporary element
   document.body.removeChild(el);
}


Code Example


// p5js Copy Text to Clipboard
// by Olaf Val
// based on example by Techoverflow
// https://techoverflow.net/2018/03/30/copying-strings-to-the-clipboard-using-pure-javascript/

let input, button;
let myText;

function setup() {
  createCanvas(400, 400);
  background(200);

  input = createInput();
  input.position(20, 20);

  button = createButton('Copy to Clipboard');
  button.position(input.x + input.width, 20);
  button.mousePressed(CopyToClipboard);

  textAlign(CENTER);
  textSize(50);
}

function CopyToClipboard() {
  myText = input.value();
  copyStringToClipboard (myText);
}

function copyStringToClipboard (str) {
   // Create new element
   var el = document.createElement('textarea');
   // Set value (string to be copied)
   el.value = str;
   // Set non-editable to avoid focus and move outside of view
   el.setAttribute('readonly', '');
   el.style = {position: 'absolute', left: '-9999px'};
   document.body.appendChild(el);
   // Select text inside element
   el.select();
   // Copy text to clipboard
   document.execCommand('copy');
   // Remove temporary element
   document.body.removeChild(el);
}