HTML5 canvas drawImage with at an angle

后端 未结 3 1083
抹茶落季
抹茶落季 2020-12-05 04:10

I am experimenting with animation in and can\'t work out how to draw an image at an angle. The desired effect is a few images drawn as usual, wit

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 05:00

    I have written a function (based on Jakub's answer) that allows user to paint an image in a X,Y position based on a custom rotation in a custom rotation point:

    function rotateAndPaintImage ( context, image, angleInRad , positionX, positionY, axisX, axisY ) {
      context.translate( positionX, positionY );
      context.rotate( angleInRad );
      context.drawImage( image, -axisX, -axisY );
      context.rotate( -angleInRad );
      context.translate( -positionX, -positionY );
    }
    

    Then you can call it like this:

    var TO_RADIANS = Math.PI/180; 
    ctx = document.getElementById("canvasDiv").getContext("2d");
    var imgSprite = new Image();
    imgSprite.src = "img/sprite.png";
    
    // rotate 45º image "imgSprite", based on its rotation axis located at x=20,y=30 and draw it on context "ctx" of the canvas on coordinates x=200,y=100
    rotateAndPaintImage ( ctx, imgSprite, 45*TO_RADIANS, 200, 100, 20, 30 );
    

提交回复
热议问题