图片在画布中没有旋转

时间:2019-02-28 15:12:57

标签: javascript canvas interaction

我已经搜索了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>

1 个答案:

答案 0 :(得分:0)

您在该行上键入的是“ Math.Pi”而不是“ Math.PI”

http.mappers.jsonPrettyPrint=true

spring.jackson.serialization.indent_output=true

objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

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