Поверните круг вокруг треугольного холста - PullRequest
0 голосов
/ 27 сентября 2018

Я хочу вращать круг вокруг треугольника, используя холст.Есть этот код из ранее, но здесь круг в середине, и прямоугольник вращается, я хочу, чтобы круг вращался и треугольник в середине.Может кто-нибудь помочь?

Вот код JS, который у меня есть:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cx = 100;
var cy = 100;
var rectWidth = 15;
var rectHeight = 10;
var rotation = 0;
requestAnimationFrame(animate);

function animate() {
  requestAnimationFrame(animate);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(cx, cy, 10, 0, Math.PI * 2);
  ctx.closePath();
  ctx.fill();
  ctx.save();
  ctx.translate(cx, cy);
  ctx.rotate(rotation);
  ctx.strokeRect(-rectWidth / 2 + 20, -rectHeight / 2, rectWidth, rectHeight);
  ctx.restore();

  rotation += Math.PI / 180;
}
<canvas id="canvas"></canvas>

Ответы [ 3 ]

0 голосов
/ 27 сентября 2018

Попробуйте следующее:

<code>    
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cx=100;
var cy=100;
var rectWidth=15;
var rectHeight=10;
var rotation=0;
requestAnimationFrame(animate);
function animate(){
    requestAnimationFrame(animate);
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.beginPath();

    var radius = 8;        
    ctx.moveTo(cx - radius, cy + radius);        
    ctx.lineTo(cx, cy - radius);        
    ctx.lineTo(cx + radius , cy + radius);        
    ctx.lineTo(cx - radius, cy + radius);        
    ctx.fill();

    ctx.save();
    ctx.translate(cx,cy);
    ctx.rotate(rotation);
    ctx.strokeRect(-rectWidth/2+20,-rectHeight/2,rectWidth,rectHeight);
    ctx.restore(); 
    rotation+=Math.PI/180;
}
</code>
0 голосов
/ 27 сентября 2018

Здесь есть альтернатива движущимся объектам без использования ctx.translate или ctx.rotate

. Мы можем использовать Math.sin и Math.cos для кругового или эллиптического движения.
Как только вы поймете этот подход, вы откроете дверь для многих возможностей, например, вы сможете сделать вращения относительно других объектов.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var rotation = 0;
setInterval(animate, 10);

function animate(rx, ry, speed) { 
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  draw(120, 80, 1)
  draw(240, 80, 10/3)
}

function draw(rx, ry, speed) {    
  var x = Math.cos(rotation) * 50 + rx
  var y = Math.sin(rotation) * 50 + ry
  
  ctx.beginPath()
  ctx.arc(x, y, 20, 0, Math.PI * 2);
  ctx.stroke();
  
  for (var i = 1; i < 8; i++) {
    x += Math.sin(rotation * i/speed) * 20
    y += Math.cos(rotation * i/speed) * 20/i
    ctx.beginPath()
    ctx.arc(x, y, 8/i, 0, Math.PI * 2);
    ctx.stroke();
  }
  rotation += Math.PI / 180;
}
<canvas id="canvas" height=170 width=400></canvas>
0 голосов
/ 27 сентября 2018

Я отредактировал ваш код, чтобы нарисовать запрошенные фигуры, и добавил комментарии, чтобы описать, что я делаю в приведенном ниже фрагменте.

var canvas = document.body.appendChild(document.createElement("canvas"));
var ctx = canvas.getContext("2d");
var cx = 100;
var cy = 100;
var rotation = 0;
requestAnimationFrame(animate);
function animate() {
    //Clear canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    //Draw center figure
    /*
    ctx.beginPath();
    ctx.arc(cx, cy, 10, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
    */
    ctx.beginPath();
    ctx.moveTo(cx - 10, cy - 10);
    ctx.lineTo(cx, cy + 10);
    ctx.lineTo(cx + 10, cy - 10);
    ctx.closePath();
    ctx.fill();
    //Rotate canvas
    ctx.save();
    ctx.translate(cx, cy);
    ctx.rotate(rotation);
    //Draw rotating object
    /*ctx.strokeRect(-rectWidth / 2 + 20, -rectHeight / 2, rectWidth, rectHeight);*/
    ctx.beginPath();
    ctx.arc(20, 0, 5, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
    //Rotate canvas back
    ctx.restore();
    //Save rotation
    rotation += Math.PI / 180;
    //Request next frame
    requestAnimationFrame(animate);
}

Похоже, вам не хватает опыта манипулирования HTML Canvas, поэтому я хотел бы порекомендовать официальное руководство по холсту MDN .

Если у вас есть дополнительные вопросы, не стесняйтесь открывать новые вопросы с более специфичными для кода проблемами в будущем.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...