在使用隐藏画布上传之前旋转图像

我试图在上传之前旋转我的图像。


我试图在空中创建一个画布,旋转它,并在里面获取数据,但它似乎不起作用,这是一个小提琴:


function rotate() {

    const img = document.getElementById("image");

  const canvas = document.createElement("canvas");

  const context = canvas.getContext("2d");

  context.rotate(90 * Math.PI / 180);

  context.drawImage(img,0,0);

  img.src = canvas.toDataURL();

  }

<img src="https://lh3.googleusercontent.com/proxy/YhFwjEreTxLoYxYc2sG_VJIp9L03YZAtQZ7FXvI46-NqSyql-rfiaLkN4G8h3Pg7fYwIYuROEBC5pBRnZPnXbgQpmB_qmCjscZ8WYKZ7Xq5j86cZRegymf_tmo2T5VdiZ-2Mfd8tXYnZXuSRh0eDBs537cmZtENW7XjLH5515uYATw" style="width: 100%; height: auto" id="image"/>

<button onclick="rotate()">

Rotate

</button>

不要考虑安全错误。

我想知道这是否是实现这一目标的好方法,如果不是,我怎么能在没有任何图书馆的情况下做到这一点?


慕容3067478
浏览 82回答 1
1回答

慕少森

您需要做一些原始代码中没有的事情:调整画布大小以匹配图像。使用 . 在画布中心执行旋转context.translate()。(请注意,我在此演示中使用数据 URI,以避免安全错误。)function rotate() {&nbsp; const img = document.getElementById("image");&nbsp; const canvas = document.createElement("canvas");&nbsp; const context = canvas.getContext("2d");&nbsp;&nbsp;&nbsp; // Make canvas the same size as img&nbsp; const cw = img.naturalHeight;&nbsp; const ch = img.naturalWidth;&nbsp; canvas.width = cw;&nbsp; canvas.height = ch;&nbsp;&nbsp;&nbsp; // Draw rotated img onto canvas&nbsp; context.translate(cw / 2, ch / 2);&nbsp; context.rotate(90 * Math.PI / 180);&nbsp; context.drawImage(img, -ch / 2, -cw / 2, ch, cw);&nbsp;&nbsp;&nbsp; // Replace img with canvas contents&nbsp; img.src = canvas.toDataURL();}<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAAAyCAYAAADLLVz8AAABO0lEQVRoge3bQQ7CMAxE0RRxYgSnQHDlsmWBit3xjL2Yv6VNm6cKqQls6/7alzvdxXRYBgS7Truh/Xk7/Hx7vGX3EmnUE/gPL3qMsjGAGZhJiCMAz4BMQWwHRCAmILYCVgB0I7YBVk68E7EFkDHhLkQ5IHOiHYhSQMUE1YgyQOXElNeSAEYnFHlNi77KqRDpgJV42WMViFRABl72HDYiDZCJlz2XiUgBVOBlx2AhlgMq8bJjMRBLATvwsmNWI5YBduJlx65ElL6JKJbj1Uv+MkDlxJTXkgB2bASprkkH7NxFU1ybCjhhC5J9D2X7wtP2a79j3pt/mQBmQDADghkQzIBgBgQzIJgBwQwIZkAwA4IZEMyAYAYEMyCYAcEMCDYO8Gj1eOKq98gn8BfU1C0D/90VzN+BYAZEWmt9ABoSb1fIlzNVAAAAAElFTkSuQmCC" style="width: 100%; max-width: 150px; height: auto" id="image" /><br /><button onclick="rotate()">Rotate</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript