Home  >  Article  >  Web Front-end  >  Canvas realizes the effect of zooming in and out of pictures according to the slider

Canvas realizes the effect of zooming in and out of pictures according to the slider

高洛峰
高洛峰Original
2017-02-25 16:08:341843browse

This article mainly introduces the example of canvas to achieve the effect of zooming in and out of pictures according to the slider. It has a very good reference value. Let’s take a look at it with the editor.

Effect picture:

Canvas realizes the effect of zooming in and out of pictures according to the slider

Picture (1) Original picture

Canvas realizes the effect of zooming in and out of pictures according to the slider

Picture (2) Zoom out After

Canvas realizes the effect of zooming in and out of pictures according to the slider

Picture (3) After zooming in

The code is as follows:

<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <title></title>
 <style type="text/css">
  #canvas1{
  box-shadow: 3px 3px 10px black;
  }
 </style>
 </head>
 <body>
 <canvas id="canvas1" width="500" height="500"></canvas>
 <input type="range" name="slider" id="silder" value="0.5" max="1" min="0" step="0.01"/>
 </body>
 <script type="text/javascript">
 var canvas = document.getElementById("canvas1");
 var context = canvas.getContext("2d");
 var slider = document.getElementById("silder");
 var scale = slider.value;
 creatImg(scale);
  slider.onmousedown = function() {
  slider.onmousemove = function () {
   scale = slider.value;
   creatImg(scale);
  }
  }
 function creatImg (scale) {
 var myImg = new Image();
 myImg.src = "https://gss0.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/902397dda144ad34ac75c376d7a20cf430ad857d.jpg"
 var imgh = canvas.height * scale;
 var imgw = canvas.width * scale;
 var x = canvas.width / 2 - imgw / 2;
 var y = canvas.height / 2 - imgh / 2
 myImg.onload = function () {
 context.clearRect(0 , 0 , canvas.width , canvas.height);
 context.drawImage(myImg , x , y ,imgw , imgh)
 }
 }
 </script>
</html>

For more canvas-related articles on how to implement image zoom-in and zoom-out effects based on the slider, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Canvas draws polygonsNext article:Canvas draws polygons