<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
</head>
<body>
<!--图片旋转实践-->
<!--作者:Saryz-->
<!--邮箱:a86115592@outlook.com-->
<!--转载请注明出处-->
<div>
<button onclick="clockwise()">顺时针</button>
<button onclick="counterclockwise()">逆时针</button>
</div>
<canvas id="canvas"></canvas>
</body>
</html>
<script>
var fWidth = 300;
var canvas = document.getElementById("canvas");
var cxt = canvas.getContext("2d");
var img = new Image();
var r = 0;
img.onload = function () {
canvas.width = fWidth;
canvas.height = Math.ceil(fWidth * img.height / img.width);
cxt.drawImage(img, 0, 0, fWidth, fWidth * img.height / img.width);
}
img.src = "case1.jpg";
/**
* 顺时针旋转
*/
function clockwise() {
r === 270 ? r = 0 : r += 90;
rotateImage()
}
/**
* 逆时针旋转
*/
function counterclockwise() {
r === 0 ? r = 270 : r -= 90;
rotateImage()
}
/**
* 旋转图片
*/
function rotateImage() {
var k = r / 90;
cxt.clearRect(0, 0, fWidth, canvas.height);
canvas.height = k % 2 === 0 ? Math.ceil(fWidth * img.height / img.width) : fWidth * img.width / img.height;
cxt.rotate(r * Math.PI / 180);
arr = [0, 0, -fWidth, -canvas.height, 0];
cxt.translate(arr[k], arr[k + 1]);
k % 2 === 0 ? drawImage(fWidth, canvas.height) : drawImage(canvas.height, fWidth);
}
/**
* 绘图
* @param w
* @param h
*/
function drawImage(w, h) {
cxt.drawImage(img, 0, 0, w, h);
}
</script>
canvas图片旋转自适应容器宽度实践
需积分: 50 57 浏览量
2018-12-12
09:33:59
上传
评论 1
收藏 12KB ZIP 举报
Saryz
- 粉丝: 0
- 资源: 7