[英]Include a variable in my HTML file from a .js file
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.
实际上在 p5 中有一个内置的 function 允许在屏幕上书写,现在它可以完美运行。
I have a sketch.js file which contains a sc
variable.我有一个包含
sc
变量的 sketch.js 文件。
I want to call the sc
variable in my index.html file to display it.我想在我的 index.html 文件中调用
sc
变量来显示它。
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.我查看了许多帖子和视频,但它始终只显示变量位于同一 HTML 文件的
<script>
header 中的方法。
How can I do this if my variable is in an other file?如果我的变量在其他文件中,我该怎么做?
files: (i'm using p5 )文件:(我正在使用 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我想在屏幕上显示“sc”值
sorry if some things could be done differently I'm really new to coding抱歉,如果可以以不同的方式完成某些事情,我对编码真的很陌生
You can put this code everywhere in your HTML file:您可以将此代码放在 HTML 文件中的任何位置:
<!DOCTYPE html>
<html>
<body>
<script>
document.write(sc);
</script>
</body>
</html>
Can you try this example?你可以试试这个例子吗?
index.html索引.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脚本.js
function printSc() {
// your logic
let d = 20
let sc
if (d <= 30) {
sc = d + 1
}
return sc
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.