javascript - 画布上没有画线
问题描述
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Asteroids</title>
<style media="screen">
</style>
</head>
<body>
<canvas id="gameCanvas" width="700" height="500"></canvas>
<script type="text/javascript">
const FPS = 30; // frames per second
const SHIP_SIZE = 30; // ship height in pixels
/* @type {HTMLCanvasElement} */
var canv = document.getElementById('gameCanvas');
var ctx = canv.getContext("2d");
var ship = {
x: canv.width / 2,
y: canv.height / 2,
r: SHIP_SIZE / 2,
a: 90 / 180 * Math.pi // Convert to radians
}
// set up the game loop
setInterval(update, 1000 / FPS);
function update() {
// draw space
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canv.width, canv.height);
// draw triangular ship
ctx.strokeStyle = "white";
ctx.lineWidth = SHIP_SIZE / 20;
ctx.beginPath();
ctx.moveTo( // nose of the ship
ship.x + 4 / 3 * ship.r * Math.cos(ship.a),
ship.y - 4 / 3 * ship.r * Math.sin(ship.a)
);
ctx.lineTo( // rear left
ship.x - ship.r * (2 / 3 * Math.cos(ship.a) + Math.sin(ship.a)),
ship.y + ship.r * (2 / 3 * Math.sin(ship.a) - Math.cos(ship.a))
);
ctx.lineTo( // rear right
ship.x - ship.r * (2 / 3 * Math.cos(ship.a) - Math.sin(ship.a)),
ship.y + ship.r * (2 / 3 * Math.sin(ship.a) + Math.cos(ship.a))
);
ctx.closePath();
ctx.stroke();
// rotate ship
// move the ship
// center dot
ctx.fillStyle = "red";
ctx.fillRect(ship.x - 1, ship.y - 1, 2, 2);
}
</script>
</body>
</html>
我不知道为什么这段代码中没有画线。每当我在 moveTo 函数之后画一条线时,它不会被绘制,但指针会转到指定位置。当我再次使用 lineTo 函数绘制线条时,只有在其中未使用 javascript Math 函数或未在之前的 moveTo 或 lineTo 函数中使用时才会绘制它。我无法理解发生了什么。谁能帮帮我吗?
解决方案
不是 ,Math.pi
是Math.PI
使用未绘制线的Math.pi
结果。NaN
只需将其更改为
a: 90 / 180 * Math.PI // Convert to radians
推荐阅读
- php - 没有变量的php mysql插入查询
- c# - SQL Server 内存中 OLTP 和会话隔离设置为快照的 ASP.NET 会话状态
- c++ - 使用 GMP 获取函数
- go - 恐慌:同步:负 WaitGroup 计数器
- doxygen - Doxygen - 显示不是变量的变量
- python-3.x - 使用代理加载 fetch_lfw_people
- teradata - 在 solaris one liner 中登录 bteq
- javascript - 单击带有“?”的href时如何防止页面刷新 多变的
- google-apps-script - 带有照片上传功能的 Google AppMaker 注册表单
- nativescript - 如何升级到 NativeScript 5?