首页 > 解决方案 > HTML5 Canvas 将圆形变为方形

问题描述

我想创建一个画布,上面有一个 100x100 像素的蓝色方块。将正方形放置在页面左侧,距顶部 50 像素。使用 javascript 为这个正方形设置动画,使其每秒向右移动 10 个像素,向下移动 10 个像素。当框碰到或越过窗口边缘时,更改相关轴的方向。

以下画布返回蓝色圆圈,但我想要 100X100px 正方形而不是圆形。我试过rect(50, 50, 50, 50);但动画停止工作

<style type="text/css">
    canvas{
        border-style: inset;
        background-color: lightgray;
        border-radius: 5px;
    }
</style>
</head>
<body style="background-color: gray;" onload="animate()">
    <canvas id="bouncyBall" width="500" height="250">
    </canvas>

    <script type="text/javascript">
        var animation;
        var centerX = 50;
        var centerY = 50;
        var radius = 20;
        var boardX = 500;
        var boardY = 250;
        var ballDx = 2;
        var ballDy = 2;

        function drawBall() {
            var content = document.getElementById("bouncyBall");
            var me = content.getContext("2d");
            me.clearRect(0,0,content.width,content.height);

            centerX = centerX + ballDx;
            centerY = centerY + ballDy;

            me.beginPath();
            me.arc(centerX,centerY,radius,0,Math.PI*2,false);
            me.stroke();
            me.fillStyle = "blue";
            me.fill();;
            me.stroke();

            if (centerY > boardY - radius || centerY - radius < 0) {
                ballDy = -1*ballDy;
            }
            if (centerX > boardX - radius || centerX < radius) {
                ballDx = -1*ballDx;
            }
        }

        function animate() {
            clearInterval(animation);
            setInterval(drawBall, 25);
        }
    </script>
</body>

标签: javascripthtml5-canvas

解决方案


你可以使用矩形

var animation;
        var centerX = 50;
        var centerY = 50;
        var radius = 0;
        var boardX = 500;
        var boardY = 250;
        var ballDx = 2;
        var ballDy = 2;
        var width = 100;
        var height = 100;

        function drawBall() {
            var content = document.getElementById("bouncyBall");
            var me = content.getContext("2d");
            me.clearRect(0,0,content.width,content.height);

            centerX = centerX + ballDx;
            centerY = centerY + ballDy;

            me.beginPath();
            me.rect(centerX,centerY,width,height);
            me.stroke();
            me.fillStyle = "blue";
            me.fill();;
            me.stroke();

            if (centerY > boardY - width || centerY - radius < 0) {
                ballDy = -1*ballDy;
            }
            if (centerX > boardX - height || centerX < radius) {
                ballDx = -1*ballDx;
            }
        }

        function animate() {
            clearInterval(animation);
            setInterval(drawBall, 25);
        }
        
        animate();
canvas{
        border-style: inset;
        background-color: lightgray;
        border-radius: 5px;
    }
<canvas id="bouncyBall" width="500" height="250">
    </canvas>


推荐阅读