图像缩放

原理图:

绿色边框为图片(img)区域,蓝色边框为canvas区域

根据上图可以得出:

dx = canvas.width / 2 - img.width / 2;
dy = canvas.height / 2 - img.height / 2;

根据 drawImage 的特性,指定起始点坐标和宽高即可实现图像缩放,配合着input[type=range]即可实现图片的缩放,这种缩放得到的是一个等比缩放的图像。

<div style='padding: 2em; border: 1px solid black'>
	<canvas id="canvas"></canvas>
	<p><input type="range" id="scale_range" min="0.5" max="3.0" value="1.0" step="0.02" style='width:100%'/></p>
</div>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var slide = document.getElementById("scale_range");
var image = new Image();
window.onload = function (e) {
  canvas.width = 640;
  canvas.height = 337;
  var scale = slide.value; // 获得初始的缩放值
  image.src = 'http://localhost/bg.jpg';
  image.onload = function () {
    // 当图片完全加载完成,在进行绘制
    drawScaleImage(scale);
    // 为slide添加鼠标移动的事件,每次鼠标在该slide上移动的时候更具新的value重新绘制image
    slide.onmousemove = function () {
      scale = slide.value; // 获得当前的缩放值
      drawScaleImage(scale); // 根据新的scale重新绘制image
    }
  }
}
function drawScaleImage(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;
  // 每次在绘制新的image之前先清除当前canvas
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.drawImage(image, dx, dy, imageWidth, imageHeight);
}

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress