首页 > 解决方案 > 图像不在画布内旋转

问题描述

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

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

<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>

标签: javascriptcanvasinteraction

解决方案


您在该行输入了“Math.Pi”而不是“Math.PI”

    ctx.rotate(degree*(Math.Pi/180));

工作小提琴:https ://jsfiddle.net/ezvj9rns/


推荐阅读