用canvas的drawImage绘制图像
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片缩放</title>
</head>
<body style="background: #000;">
<canvas id="canvas" style="display: block;margin:0 auto;background: #fff;"></canvas>
<input type="range" name="" id="scale-canvas" min="0.5" max="3.0" value="1.0" step="0.01" style="display: block;width:300px;margin:0 auto;">
<script type="text/javascript">
var range = document.getElementById('scale-canvas');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var image = new Image();
window.onload = function(){
canvas.width = 418;
canvas.height =435;
image.src = '2.jpg';
var scale = range.value;
image.onload = function () {
drawImageByRange(scale);
range.onmousemove = function () {
scale = range.value;
drawImageByRange(scale);
}
}
}
function drawImageByRange(scale){
var imageWidth = canvas.width * scale ;
var imageHeight = canvas.height * scale ;
var dx = canvas.width / 2 - imageWidth / 2;
var dy = canvas.height / 2 - imageHeight / 2;
context.clearRect( 0 , 0 ,canvas.width , canvas.height);
context.drawImage(image, dx , dy , imageWidth , imageHeight );
}
</script>
</body>
</html>
网友评论