canvas----3 rotate旋转

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      body {
        background: #000000;
      }
      canvas {
        background: #ffffff;
        transition: translate 0.5s;
      }
    </style>
  </head>
  <body>
    <input type="button" value="<--" />
    <input type="button" value="-->" />
    <div>
      <img src="abc.png" id="img1" />
    </div>
  </body>
  <script>
    var ainput = document.getElementsByTagName("input");
    var oImage = document.getElementById("img1");
    var oc, oGC;
    var yImg = new Image();
    var iNow = 0;
    yImg.onload = function() {
      draw(oImage);
    };

    yImg.src = oImage.src;
    function draw(imgo) {
      oc = document.createElement("canvas");
      oGC = oc.getContext("2d");
      oc.width = imgo.width;
      oc.height = imgo.height;
      imgo.parentNode.replaceChild(oc, imgo);
      let scale = imgo.width / imgo.height;
      oGC.drawImage(yImg, 0, 0, imgo.width, imgo.height);
    }
    ainput[0].onclick = function() {
      
      if(iNow>3){
          iNow =1
      }else{
        iNow++;
      }
      toChange();
    };
    ainput[1].onclick = function() {
      
      if(iNow<0){
          iNow=4
      }else{
        iNow--
      }
      toChange()
    };
    function toChange() {
        console.log(iNow)
      switch (iNow) {
        case 1:
         oGC.save()
          oc.width = oImage.height;
          oc.height = oImage.width;
          oGC.rotate((90 * Math.PI) / 180);
          oGC.drawImage(yImg, 0, -oImage.height, oImage.width, oImage.height);
          oGC.restore()
            break;
        case 2:
        oGC.save()
          oc.width = oImage.width;
          oc.height = oImage.height; 
          oGC.rotate((180 * Math.PI) / 180);
          oGC.drawImage(yImg,-oImage.width,  -oImage.height, oImage.width, oImage.height);
          oGC.restore()
          break;
          case 3:
          oGC.save()
          oc.width = oImage.height;
          oc.height = oImage.width; 
          oGC.rotate((270 * Math.PI) / 180);
          oGC.drawImage(yImg,-oImage.width,  0, oImage.width, oImage.height);
          oGC.restore()
          break;
          case 4:
          oGC.save()
          oc.width = oImage.width;
          oc.height = oImage.height; 
          oGC.rotate((360 * Math.PI) / 180);
          oGC.drawImage(yImg,0, 0, oImage.width, oImage.height);
          oGC.restore()
          break;
        default:
          break;
      }
    }
  </script>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_41069726/article/details/89431017