我正在 Khan Academy 和 Codecademy 上学习 JavaScript。我刚刚开始学习。我真的很喜欢 Khan 教授 JS 的方式,但是,除了 Khan 的引擎之外,我没有找到任何方法可以将我所学到的知识应用到其他地方。 Khan 专注于图形而不是基于控制台的命令。
我真正寻找的是一种方法,可以利用我在 Khan(图形)和 Codecademy(控制台)上学到的知识,并在我的 PC 上离线“运行”它们。例如,我将能够“运行”所有这些功能等:
confirm()、prompt()、rect()、triangle()、ellipse()、console.log()等
那么,谁能向我解释一下如何在我的 PC 上离线编写、保存和运行此类 JavaScript 程序?
最佳答案
可汗学院的编程使用 JavaScript 语言以及 ProcessingJS 库。
这是一个源自 Processing.js Quick Start 的独立程序示例。这会执行一个非常简单的动画。
图形函数将匹配 the documentation at khanacademy.org还有here .
要运行此程序,您需要从 here 下载文件“processing.js”并将以下内容保存为“hello.html”(或任何您想要的名称),然后用浏览器打开“hello.html”。
<script src="processing.js"></script>
<script type="application/processing" data-processing-target="pjs">
void setup() {
size(200, 200);
stroke(0), strokeWeight(2);
println('hello web!');
}
void draw() {
background(100); // clear the frame
ellipse(abs(frameCount%400-200), 50, 25, 25);
}
</script>
<canvas id="pjs"> </canvas>
替代方案:高级 JavaScript 编程风格
这是一个基于 Processing.js Quick Start 中的片段的独立 JavaScript 程序示例-- 这会绘制(并动画)一个小型模拟时钟。
可用的图形函数与上面相同,但这里它们需要前缀processing
——下面的sketchProc()的参数
。请特别注意对 processing.line()
的调用。
运行此程序的说明与上面相同 - 只需将以下 .html 文件与文件 processing.js
一起放入文件夹中...
<!DOCTYPE html>
<html>
<head>
<title>Hello Web - Processing.js Test</title>
<script src="processing.js"></script>
</head>
<body>
<h1>Processing.js Test</h1>
<p>This is my first Processing.js web-based sketch:</p>
<canvas id="canvas"></canvas>
<script>
function sketchProc(processing) {
processing.draw = function() {
var centerX = processing.width / 2, centerY = processing.height / 2;
var maxArmLength = Math.min(centerX, centerY);
function drawArm(position, lengthScale, weight) {
processing.strokeWeight(weight);
processing.line(centerX, centerY,
centerX + Math.sin(position * 2 * Math.PI) * lengthScale * maxArmLength,
centerY - Math.cos(position * 2 * Math.PI) * lengthScale * maxArmLength);
}
processing.background(224);
var now = new Date();
var hoursPosition = (now.getHours() % 12 + now.getMinutes() / 60) / 12;
drawArm(hoursPosition, 0.5, 5);
var minutesPosition = (now.getMinutes() + now.getSeconds() / 60) / 60;
drawArm(minutesPosition, 0.80, 3);
var secondsPosition = now.getSeconds() / 60;
drawArm(secondsPosition, 0.90, 1);
};
}
var canvas = document.getElementById("canvas");
var processingInstance = new Processing(canvas, sketchProc);
</script>
</body>
</html>
关于JavaScript:显示图形,如 rect()、triangle()、ellipse() 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22950665/