图像缩放
一.首先分析原理
如图所示:每一次都显示整个图像,只不过显示整个图像时候,无论是放大还是缩小,显示的目标图像的左上角坐标不一样,而此时的sx,sy就是目标图像的左上角的坐标。当图像放大时(scale>1),sx,sy都是负数,目标图像将从canvas的外部显示,不过在canvas画布外面是不显示的,会被自动裁;当图像缩小时(scale<1),sx,sy都正数,目标图像就会在canvas画布里面显示
sx = canvas.width /2 - imageWidth / 2;
sy = canvas.height / 2 - imageHeight / 2;
二.所有要用知识点
<input type="range" id="scale-range" min="0.5" max="3.0" step="0.01" value="1.0" style="display:block;margin:20px auto;width:800px"/>
step是每一步滑动的进度值
2.拖动滑块控件的获取值
slider.onmousemove = function(){
scale = slider.value;
}
3.图片的加载:
var image = new Image();
image.src = "timg.jpg";
image.onload = function(){
context.drawImage( image , dx ,dy , imageWidth , imageHeight );
}
4.当图像充满画布时,又要重新绘制图像,要记得清空画布
context.clearRect( 0 , 0 , canvas.width , canvas.height );
三.代码
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body{
background: black;
}
#scale-range{
display:block;
margin:20px auto;
width:800px;
}
#canvas{
display:block;
margin:0 auto;
border:1px solid #aaa;
}
</style>
</head>
<body>
<canvas id="canvas">您的浏览器尚不支持canvas </canvas>
<input type="range" id="scale-range" min="0.5" max="3.0" step="0.01" value="1.0"/>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var slider = document.getElementById("scale-range");
var image = new Image();
var imgW=1024;
var imgH=750;
canvas.width = 1024;
canvas.height = 750;
window.onload = function(){
var scale = slider.value;
image.src = "timg.jpg";
image.onload = function(){
drawImageByScale( scale );
slider.onmousemove = function(){
scale = slider.value;
drawImageByScale( scale );
}
}
}
function drawImageByScale( scale ){
var imageWidth = imgW * scale; //imgW,imgH是图片的大小
var imageHeight =imgH * scale;
dx = canvas.width /2 - imageWidth / 2;//目标图像的坐标
dy = canvas.height / 2 - imageHeight / 2;//目标图像的坐标
context.clearRect( 0 , 0 , canvas.width , canvas.height );
context.drawImage( image , dx ,dy , imageWidth , imageHeight );
}
</script>
</body>
</html>