canvas drawImage設置圖片居中,拖動,縮放

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    html,body,#app {
      width:100%;
      height:100%;
      border:0;
      margin:0;
      padding:0;
    }
    #canvas{
      width:100%;
      height:100%;
    }
  </style>
</head>

<body>
  <div id="app">
    <canvas id="canvas"></canvas>
  </div>
  <script>
    var canvas, context;
var imageWidth, imageHeight;
var img,
  imgX = 0,
  imgY = 0,
  imgScale = 1;
function loadImg() {
  img = new Image();
  img.onload = function () {
    imgX = (canvas.width - img.width) / 2;
    imgY = (canvas.height - img.height) / 2
    drawImage();
  }
  img.src = 'http://127.0.0.1:56398/%E4%B8%89%E5%93%A5%E5%B0%8F%E8%88%9E.jpeg';
}
function drawImage() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.drawImage(
    img, //規定要使用的圖像、畫布或視頻。
    0, 0, //開始剪切的 x 座標位置。
    img.width, img.height,  //被剪切圖像的高度。
    imgX, imgY,//在畫布上放置圖像的 x 、y座標位置。
    img.width * imgScale, img.height * imgScale  //要使用的圖像的寬度、高度
  );
  canvasEventsInit()
}
function canvasEventsInit() {
  canvas.onmousedown = function (event) {
    var pos = windowToCanvas(event.clientX, event.clientY);

    canvas.onmousemove = function (evt) {
      canvas.style.cursor = 'move';
      var posl = windowToCanvas(evt.clientX, evt.clientY);
      var x = posl.x - pos.x;
      var y = posl.y - pos.y;
      pos = posl;
      imgX += x;
      imgY += y;
      drawImage();
    };
    canvas.onmouseup = function () {
      canvas.onmousemove = null;
      canvas.onmouseup = null;
      canvas.style.cursor = 'default';
    };
    document.onmouseup = function() {
      canvas.onmousemove = null;
      canvas.onmouseup = null;
      canvas.style.cursor = 'default';
      document.onmouseup = null;
    }
  };

  canvas.onmousewheel = canvas.onwheel = function (event) {
    var pos = windowToCanvas(event.clientX, event.clientY);
    var n = 1.1;
    var n2 = (1/1.1).toFixed(2);
    event.wheelDelta = event.wheelDelta ? event.wheelDelta : (event.deltalY * (-40));
    if (event.wheelDelta > 0) {
      imgScale *= n;
      imgX = imgX * n - pos.x * (n-1);
      imgY = imgY * n - pos.y * (n-1);
    } else {

      imgScale *= n2;
      imgX = imgX *n2+ pos.x *(1-n2);
      imgY = imgY *n2 + pos.y *(1-n2);
    }
    drawImage();
  };
}


/*座標轉換*/
function windowToCanvas(x, y) {
  var box = canvas.getBoundingClientRect();
  return {
    x: x - box.left - (box.width - canvas.width) / 2,
    y: y - box.top - (box.height - canvas.height) / 2
  };
}
(function int() {
  canvas = document.getElementById('canvas');
  canvas.width = canvas.getBoundingClientRect().width;
  canvas.height = canvas.getBoundingClientRect().height;
  context = canvas.getContext('2d');
  loadImg();

})();
      
  </script>
</body>

</html>
相關文章
相關標籤/搜索