Skip to content

Commit 707a886

Browse files
authored
Update liveSketch.js
Implemented dynamically adjusts the height of the canvas in p5.js when the text content exceeds the current visible area. This ensures that all text remains visible without requiring manual scrolling or truncation
1 parent a067670 commit 707a886

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

content/examples/Basics/Data/CharactersStrings/liveSketch.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,34 +19,48 @@
1919
function runLiveSketch(s) {
2020
var letter = '';
2121
var words = 'Begin...';
22+
var lineHeight = 36;
23+
var bottomPadding = 5;
2224

2325
s.setup = () => {
2426
s.createCanvas(640, 360);
25-
// Create the font
2627
s.textFont('Source Code Pro', 36);
28+
s.textWrap(s.CHAR);
2729
};
2830

2931
s.draw = () => {
3032
s.background(0); // Set background to black
3133

32-
// Draw the letter to the center of the screen
34+
// Draw the letter and status text
3335
s.textSize(14);
3436
s.fill(255);
3537
s.noStroke();
3638
s.text('Click on the program, then type to add to the String', 50, 50);
3739
s.text('Current key: ' + letter, 50, 70);
3840
s.text('The String is ' + words.length + ' characters long', 50, 90);
3941

42+
// Calculate the number of lines of text
4043
s.textSize(36);
41-
s.text(words, 50, 120, 540, 300);
44+
let textWidth = 540;
45+
let textHeight = s.textAscent() + s.textDescent();
46+
47+
// Calculate the number of lines needed for the text
48+
let numLines = s.ceil(s.textWidth(words) / textWidth);
49+
let contentHeight = numLines * textHeight + 120 + bottomPadding;
50+
51+
// Resize canvas if the content height exceeds the current canvas height
52+
if (contentHeight > s.height) {
53+
s.resizeCanvas(640, contentHeight);
54+
}
55+
s.text(words, 50, 120, textWidth, s.height);
4256
};
4357

4458
s.keyPressed = () => {
45-
// The variable "key" always contains the value
46-
// of the most recent key pressed.
59+
4760
if ((s.key >= 'A' && s.key <= 'z') || s.key == ' ') {
4861
letter = s.key;
4962
words = words + s.key;
5063
}
5164
};
5265
}
66+

0 commit comments

Comments
 (0)