canvas實現的圖片縮放程式碼例項

admin發表於2017-02-13
分享一段程式碼例項,它實現了拖動底部滑軸調整圖片縮放效果的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
#canvas {
  display:block;
  margin:0 auto;
  border:1px solid #aaa;
}
#range {
  display:block;
  margin:20px auto;
  width:800px;
}
</style>
<script>
window.onload = function () {
  var canvas = document.getElementById("canvas")
  var context = canvas.getContext("2d")
  var range = document.getElementById("range")
  var image = new Image()
  function drawImageByScale(scale) {
    var imageWidth = 308 * scale
    var imageHeight = 220 * 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)
  }
  canvas.width=308
  canvas.height=220
  var scale=range.value
  image.src = "demo/js/img/pretty.jpg"
  image.onload=function(){
    drawImageByScale(scale)
    range.onmousemove=function(){
      scale=range.value
      drawImageByScale(scale)
    }
  }
}
</script>
</head>
<body>
<canvas id="canvas"></canvas>
<input type="range" id="range" min="0.5" max="3.0" step="0.01" value="1">
</body>
</html>

相關文章