图片未在 canvas 内旋转

Image isn't rotating within canvas

我搜索了 Whosebug 并找到了一些有助于旋转图像的代码,但它不起作用。我没有看到任何错误,它正在获取弧度和度数,所以应该可以正常工作,但是 canvas 中的图像不会旋转。

当用户点击 canvas 然后移动鼠标时,代码应该开始旋转图像。当他们在页面上或 canvas 上释放鼠标时,它应该停止图像的旋转。

<script type="text/javascript">

    var mouseDown = false;
    var intID;
    var mouse_x = 0;
    var mouse_y = 0;        
    var canvas;            
    var img;

    function init()
    {
        canvas = document.getElementById("wheelCanvas");
        img = new Image();
        img.src = 'images/wheel.png';

        img.onload = function() {
            var ctx = canvas.getContext("2d");        

            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(img, 0, 0, img.width, img.height);
        }

        canvas.onmousedown = function(event)
        {
            mouseDown = true;
            intID = setInterval(rotateWheel, 100);                
        }

        canvas.onmouseup = function(event)
        {
            mouseDown = false;
            clearInterval(intID);
        }

        canvas.onmousemove = function(event)
        {
            if(mouseDown)
            {
                mouse_x = event.pageX;
                mouse_y = event.pageY;
            }
        }

        document.onmouseup = function(event)
        {
            mouseDown = false;
            clearInterval(intID);
        }
    }

    function rotateWheel()
    {
        var ctx = canvas.getContext("2d"); 

        var center_x = canvas.width / 2;
        var center_y = canvas.height / 2;
        var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
        var degree = Math.round((radians * (180 / Math.PI) * -1) + 180);

        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.save();
        ctx.translate(425,425);
        ctx.rotate(degree*(Math.Pi/180));
        ctx.drawImage(img, -img.width/2, -img.height/2);
        ctx.restore();
        console.log(degree);

        if(!mouseDown) { clearInterval(intID); }
    }
</script>

您在第

行输入了 "Math.Pi" 而不是 "Math.PI"
    ctx.rotate(degree*(Math.Pi/180));

工作fiddle:https://jsfiddle.net/ezvj9rns/