我正在尝试绘制一系列绕中心点旋转的圆,这是非常非常基本的版本: https://mgvez.github.io/jsorrery/
到目前为止,我已经解决了这个问题,但是形状已经填充,我不确定为什么。它看起来确实很酷,但不是我想要的;)
var origin_x = 200;
var origin_y = 200;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
class planet {
constructor(orbital_velocity, orbital_radius, radius) {
this.orbital_velocity = orbital_velocity;
this.orbital_radius = orbital_radius;
this.radius = radius;
this.draw()
}
draw() {
const theta = t*this.orbital_velocity
const x = origin_x + this.orbital_radius*Math.cos(theta)
const y = origin_y + this.orbital_radius*Math.sin(theta)
ctx.arc(x, y, this.radius, 0, 2*Math.PI, 'anticlockwise')
ctx.fill();
}
}
let t = 0;
window.setInterval(function(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
const a = new planet(2*Math.PI, 30, 1 );
const b = new planet(Math.PI, 50, 1 );
const c = new planet(0.5*Math.PI, 70, 1 );
const d = new planet(0.25*Math.PI, 90, 1 );
t += 0.1;
}, 40);
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col text-center">
<canvas id="canvas" width="400" height="400" />
</div>
</div>
</div>
</body>
</html>
我已经阅读了文档,但我不知道为什么会这样...我需要填充各个圆(弧),而不是它们之间的形状...
答案 0 :(得分:2)
您需要调用ctx.beginPath()
和ctx.closePath()
,否则画布会认为您正在绘制一个复杂的元素/多边形并尝试填充它。
var origin_x = 200;
var origin_y = 200;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
class planet {
constructor(orbital_velocity, orbital_radius, radius) {
this.orbital_velocity = orbital_velocity;
this.orbital_radius = orbital_radius;
this.radius = radius;
this.draw()
}
draw() {
const theta = t*this.orbital_velocity
const x = origin_x + this.orbital_radius*Math.cos(theta)
const y = origin_y + this.orbital_radius*Math.sin(theta)
ctx.beginPath();
ctx.arc(x, y, this.radius, 0, 2*Math.PI, 'anticlockwise')
ctx.fill();
ctx.closePath();
}
}
let t = 0;
window.setInterval(function(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
const a = new planet(2*Math.PI, 30, 1 );
const b = new planet(Math.PI, 50, 1 );
const c = new planet(0.5*Math.PI, 70, 1 );
const d = new planet(0.25*Math.PI, 90, 1 );
t += 0.1;
}, 40);
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col text-center">
<canvas id="canvas" width="400" height="400" />
</div>
</div>
</div>
</body>
</html>