EDIT: Thanks everyone for your help. There is actually a built-in function in p5 that allow to write on screen and now, it work perfectly.
I have a sketch.js file which contains a sc
variable.
I want to call the sc
variable in my index.html file to display it.
I looked at many posts and videos but, it always only shows how to do it if the variable is in the <script>
header of the same HTML file.
How can I do this if my variable is in an other file?
files: (i'm using p5 )
function setup() {
createCanvas(400, 400);
//Square variables
sQx = 5;
sQy = 5;
sQs = 20;
speed = 5;
//Rectangle variables
Rx = 300
Ry = 300
Rw = 40
Rh = 70
//Points variable
Px = 300
Py = 300
Ps = 10
//Score variable
sc = 0
}
function draw() {
background(100);
color(255, 204, 0)
square(sQx, sQy, sQs)
color(255, 204, 0)
//Makes the Square move
if (keyIsDown(UP_ARROW)) {
sQy -= speed
} else if (keyIsDown(DOWN_ARROW)) {
sQy += speed
} else if (keyIsDown(LEFT_ARROW)) {
sQx -= speed;
} else if (keyIsDown(RIGHT_ARROW)) {
sQx += speed;
}
//rect(Rx, Ry, Rw, Rh)
//Create the points
square(Px, Py, 10)
// Detect if Square is on the points and change the points place
let d = dist(sQx, sQy, Px, Py)
if (d <= 30) {
let RdX = random(0, 400)
Px = RdX
let RdY = random(0, 400)
Py = RdY
sc = sc + 1
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sketch</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="libraries/p5.min.js"></script>
<script src="libraries/p5.sound.min.js"></script>
<script src="sketch.js">
</script>
</head>
<body>
<div id="sc"></div>
<script>
let value = printSc()
document.getElementById("sc").innerHTML = "your score is:" + value
</script>
<div id="sc"></div>
</body>
</html>
I want display the "sc" value on the screen
sorry if some things could be done differently I'm really new to coding
You can put this code everywhere in your HTML file:
<!DOCTYPE html>
<html>
<body>
<script>
document.write(sc);
</script>
</body>
</html>
Can you try this example?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js"></script>
<title>Document</title>
</head>
<body>
<div id="sc"></div>
</body>
<script>
let value = printSc()
document.getElementById("sc").innerHTML = value
</script>
</html>
script.js
function printSc() {
// your logic
let d = 20
let sc
if (d <= 30) {
sc = d + 1
}
return sc
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.