我想在画布上画星。我成功的价值如下:
源代码如下:
line = (r, s, context) ->
context.beginPath()
context.moveTo(250, 250)
context.lineTo(
250 + r * Math.cos(s * 2 * Math.PI),
250 + r * Math.sin(s * 2 * Math.PI)
)
context.stroke()
window.onload = ->
canvas = document.getElementById("myCanvas")
context = canvas.getContext("2d")
for i in [1..10]
line(200, i / 10, context)
return
在下一步中,我尝试设置行数。
CoffeeScript源代码如下:
line = (r, s, context) ->
context.beginPath()
context.moveTo(250, 250)
context.lineTo(
250 + r * Math.cos(s * 2 * Math.PI),
250 + r * Math.sin(s * 2 * Math.PI)
)
context.stroke()
isInt = (n) ->
(n % 1) == 0;
root = exports ? this
root.star = ->
canvas = document.getElementById("myCanvas")
context = canvas.getContext("2d")
n = document.fm.int.value
if(isInt(n))
for i in [1..n]
line(200, i / n, context)
return
else
alert("is not integer")
return
完整的html页面源代码如下:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
(function() {
var isInt, line, root;
line = function(r, s, context) {
context.beginPath();
context.moveTo(250, 250);
context.lineTo(250 + r * Math.cos(s * 2 * Math.PI), 250 + r * Math.sin(s * 2 * Math.PI));
return context.stroke();
};
isInt = function(n) {
return (n % 1) === 0;
};
root = typeof exports !== "undefined" && exports !== null ? exports : this;
root.star = function() {
var canvas, context, i, n, _i;
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
n = document.fm.int.value;
if (isInt(n)) {
for (i = _i = 1; 1 <= n ? _i <= n : _i >= n; i = 1 <= n ? ++_i : --_i) {
line(200, i / n, context);
}
} else {
alert("is not integer");
}
};
}).call(this);
</script>
</head>
<body>
<form name="fm" onsubmit="star()">
Integer:
<input type="text" name="int" size="5" />
<input type="submit" value="Draw">
</form>
<canvas id="myCanvas" width="500" height="500"></canvas>
</body>
</html>
然后明星出现片刻,但随后明星消失了。如何保持星形显示?
谢谢你的善意。