js canvas绘图 绕中心点任意角度旋转

本文介绍了一个使用HTML5 Canvas实现图片旋转的功能。通过获取用户输入的角度值,该示例能够动态地旋转并绘制指定的图片。文章包含完整的HTML、CSS及JavaScript代码,并详细展示了如何设置画布尺寸、清除背景、进行坐标系转换以及最终将图片绘制到画布上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
 
<!DOCTYPE html>
<html>
<head>
    <title>canvasTest</title>
</head>
<style type="text/css">
    .imgbox img {
        width: 100%
    }
    .canvasbox canvas {
        width: 100%
    }
</style>

<body>
<div class="imgbox"><img id="img" src="./img/aaa.png"></div>
<div>
    <input type="number" id="number" name="" placeholder="输入旋转角度">
    <button οnclick="drawImgToCanvas()">draw</button>
</div>
<div class="canvasbox">
    <canvas id="canvas"></canvas>
</div>
<script type="text/javascript">
  let drawImgToCanvas = () => {
    let rotate = document.getElementById('number').value * 1
    let canvas = document.getElementById('canvas')
    let context = canvas.getContext('2d')
    let img = new Image()
    img.src = './img/aaa.png'
    img.onload = () => {
      // corssOrigin must be set before the url
      img.setAttribute('crossOrigin', 'Anonymous')
      if (rotate < 0) {
        rotate = 360 + rotate
      }
      rotate = rotate % 360

      if (rotate > 45 && rotate < 135) { // 90 宽高颠倒
        canvas.width = img.height
        canvas.height = img.width
      } else if (rotate > 225 && rotate < 315) { // 270 宽高颠倒
        canvas.width = img.height
        canvas.height = img.width
      } else {
        canvas.width = img.width
        canvas.height = img.height
      }
      context.clearRect(0, 0, canvas.width, canvas.height)


      context.translate(canvas.width / 2, canvas.height / 2)
      context.rotate(rotate * Math.PI / 180)
      context.translate(-canvas.width / 2, -canvas.height / 2)
      context.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2)
      context.translate(canvas.width / 2, canvas.height / 2)
      context.rotate(-rotate * Math.PI / 180)
      context.translate(-canvas.width / 2, -canvas.height / 2)
      context.restore()
    }
  }
</script>
</body>
</html>

demo地址 https://xingyanhai.github.io/17-04-12/canvasRotate/canvasTest.html

                
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值