javascript 如何在画布上移动矩形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9975232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:23:41  来源:igfitidea点击:

How to move rectangle on canvas

javascriptjqueryjavascript-events

提问by pravin

I use canvas in my application using JavaScript. On that canvas I draw one rectangle. I want to move rectangle with the help of mouse(e.g moving slider) how to move that rectangle using JavaScript or J-query.

我使用 JavaScript 在我的应用程序中使用画布。在那个画布上我画了一个矩形。我想在鼠标的帮助下移动矩形(例如移动滑块)如何使用 JavaScript 或 J-query 移动该矩形。

回答by Yoshi

On a second reading, I think I misunderstood your question, so here's an updated version:

在第二次阅读时,我想我误解了你的问题,所以这里有一个更新的版本:

http://jsfiddle.net/HSMfR/4/

http://jsfiddle.net/HSMfR/4/

$(function () {
  var
    $canvas = $('#canvas'),
    ctx = $canvas[0].getContext('2d'),
    offset = $canvas.offset(),
    draw,
    handle;

  handle = {
    color: '#666',
    dim: { w: 20, h: canvas.height },
    pos: { x: 0, y: 0 }
  };

  $canvas.on({
    'mousedown.slider': function (evt) {
      var grabOffset = {
        x: evt.pageX - offset.left - handle.pos.x,
        y: evt.pageY - offset.top - handle.pos.y
      };

      // simple hit test
      if (   grabOffset.x >= 0
          && grabOffset.x <= handle.dim.w
          && grabOffset.y >= 0
          && grabOffset.x <= handle.dim.h
      ) {
        $(document).on({
          'mousemove.slider': function (evt) {
            handle.pos.x = evt.pageX - offset.left - grabOffset.x;

            // prevent dragging out of canvas
            if (handle.pos.x < 0) {
              handle.pos.x = 0;
            }

            if (handle.pos.x + handle.dim.w > canvas.width) {
              handle.pos.x = canvas.width - handle.dim.w;
            }

            //handle.pos.y = evt.pageY - offset.top - grabOffset.y;
          },
          'mouseup.slider': function () {
            $(document).off('.slider');
          }
        });
      }
    }
  });

  draw = function() {
    var val = (100 * (handle.pos.x / (canvas.width - handle.dim.w))).toFixed(2) + '%';

    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.fillStyle = handle.color;
    ctx.fillRect(handle.pos.x, handle.pos.y, handle.dim.w, handle.dim.h);

    ctx.textBaseline = 'hanging';
    ctx.font = '12px Verdana';
    ctx.fillStyle = '#333';
    ctx.fillText(val, 4, 4);
    ctx.fillStyle = '#fff';
    ctx.fillText(val, 3, 3);
  };

  setInterval(draw, 16);
});


prev version:

上一个版本

Very simple solution to extend upon:

扩展的非常简单的解决方案:

http://jsfiddle.net/HSMfR/

http://jsfiddle.net/HSMfR/

$(function () {
  var
    ctx = $('#canvas')[0].getContext('2d'),
    $pos = $('#pos'),
    draw;

  draw = function() {
    var x = ($pos.val() / 100) * (ctx.canvas.width - 20);

    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.fillStyle = 'black';
    ctx.fillRect(x, 0, 20, 20);
  };

  setInterval(draw, 40);
});

回答by Simon Sarris

A Canvas is literally just a surface that you paint on and none of the things you paint are objects.

画布实际上只是您绘画的表面,您绘画的任何东西都不是对象。

If you want to pretend they are objects (like moving around a rectangle or a line) then you need to keep track of everythingand do all the hit-testing and re-painting yourself .

如果您想假装它们是对象(例如围绕矩形或直线移动),那么您需要跟踪所有内容并自己进行所有命中测试和重新绘制。

I wrote a gentle introduction articleon getting started by making rectangles that you can select and drag around. Give that a read.

我写了一篇简单的介绍文章介绍如何制作可以选择和拖动的矩形。读一读。