javascript - 有没有办法让这个 Action 变成圆形而不是方形?

标签 javascript

我只是在玩 Canvas ,我试图让它以圆形而不是方形移动,这可能吗?如果是的话,怎么办?

这是我到目前为止所拥有的,我不知道如何让它绕圈移动。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>derp</title>
</head>
<body>

<canvas id="canvas" width="800" height="500" style="border:1px solid #d3d3d3;"></canvas>

<script type="text/javascript" language="JavaScript">
    var height = 500;
    var width = 800;
    var radius = 100;
    var x = 100;
    var y = 100;
    var xass = 0;

    function draw(){
        if(x == 100 && y == 100){
            xass = 0
        }
        if(x == 700 && y == 100){
            xass = 1
        }
        if(x == 700 && y == 400){
            xass = 2
        }
         if(x == 100 && y == 400){
            xass = 3
        }
        if( xass == 0){
            x++
        }
        else if(xass == 1){
            y++
        }
        else if(xass == 2){
            x--
        }
        else if(xass == 3){
            y--
        }

        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");

        ctx.clearRect(0, 0, 800, 500);
        ctx.beginPath();
        ctx.moveTo(400,250);
        ctx.lineTo(x,y);
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(x,y,5,0,2*Math.PI);
        ctx.stroke();
        ctx.fill();
        ctx.beginPath();
        ctx.arc(400,250,15,0,2*Math.PI);
        ctx.stroke();
    }
</script>

<style>
    canvas {
           margin-left: auto;
           margin-right: auto;
           display: block;
    }
</style>
</body>
</html>

最佳答案

查看此https://jsfiddle.net/kup3qe5c/2/我刚刚使用了圆函数(数学)

var height = 500;
var width = 800;
var radius = 150;
var x,y;

var step = 2*Math.PI/20;
var h = width/2; 
var k = height/2;

var theta = 0;

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");

function draw(){
    theta += step
    x = h + radius*Math.cos(theta);
    y = k - radius*Math.sin(theta);

    ctx.clearRect(0, 0, 800, 500);
    ctx.beginPath();
    ctx.moveTo(400,250);
    ctx.lineTo(x,y);
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(x,y,5,0,2*Math.PI);
    ctx.stroke();
    ctx.fill();
    ctx.beginPath();
    ctx.arc(400,250,15,0,2*Math.PI);
    ctx.stroke();
}

setInterval(draw,100);

关于javascript - 有没有办法让这个 Action 变成圆形而不是方形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34268999/

相关文章:

javascript - 通过 HTTPS 页面的 HTTP Ajax 请求

javascript - 输入 Controller 调用函数 angularJS

JavaScript + HTML5 : Audio will only play once under certain circumstances

javascript - 如何将 javascript 示例与外部 js 一起使用?滚动后突出显示 div

Javascript尾递归而不是循环

javascript - Facebook JS SDK : access_token in plain text and security

javascript - Handlebars 将字符串数组转换为变量数组

javascript - 如何使用jquery获取下拉值并在文本框中显示?

javascript - if/else 列出可能的日期条件永远不会成功

javascript - 我不明白 javascript 的每个循环