1 回答
TA贡献2019条经验 获得超9个赞
您需要做一些原始代码中没有的事情:
调整画布大小以匹配图像。
使用 . 在画布中心执行旋转
context.translate()
。
(请注意,我在此演示中使用数据 URI,以避免安全错误。)
function rotate() {
const img = document.getElementById("image");
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
// Make canvas the same size as img
const cw = img.naturalHeight;
const ch = img.naturalWidth;
canvas.width = cw;
canvas.height = ch;
// Draw rotated img onto canvas
context.translate(cw / 2, ch / 2);
context.rotate(90 * Math.PI / 180);
context.drawImage(img, -ch / 2, -cw / 2, ch, cw);
// Replace img with canvas contents
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>
添加回答
举报