canvas控制图片的放大与缩小
2020-09-28 本文已影响0人
在小白的路上越走越远
<html>
<head>
<title>Scaling Images</title>
<style>
body {
background: rgba(100, 145, 250, 0.3);
}
#canvas {
margin-left: 20px;
margin-right: 0;
margin-bottom: 20px;
border: thin solid #aaaaaa;
cursor: crosshair;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="420"> Canvas not supported </canvas>
</body>
<script>
// 创建画布绘图为2d的环境
var canvas = document.getElementById("canvas")
let context = canvas.getContext("2d")
// Functions.....................................................
function drawImage() {
context.clearRect(0, 0, canvas.width, canvas.height); // 清空画版
//缩放后图片的宽高
image.width = image.width * imgScale;
image.height = image.height * imgScale;
// 左上角开始的x,y轴(可以理解为绝对定位的中心点)
let centerX = canvas.width / 2 - image.width / 2;
let centerY = canvas.height / 2 - image.height / 2;
// 绘制
context.drawImage(image, centerX, centerY, image.width, image.height);
}
// Event Handlers................................................
onmousewheel = function (e) {
context.clearRect(0, 0, canvas.width, canvas.height);
if (e.wheelDelta > 0) { //向前滚动放大
imgScale = 2;
drawImage();
} else { // 向后滚动缩小
imgScale = 0.5;
drawImage();
}
};
// Initialization................................................
let image = new Image()
let imgScale = 1;
image.src = "test.jpg";
image.width = 200;
image.height = 250;
image.onload = function (e) {
drawImage();
};
</script>
</html>