如何在画布上移动矩形

时间:2012-04-02 11:03:52

标签: javascript jquery javascript-events

我使用JavaScript在我的应用程序中使用canvas。在那个画布上我绘制了一个矩形。我想借助鼠标移动矩形(例如移动滑块)如何使用JavaScript或J查询移动该矩形。

2 个答案:

答案 0 :(得分:7)

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

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);
});

上一版本

非常简单的解决方案:

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);
});

答案 1 :(得分:7)

Canvas实际上只是您绘制的表面,并且您绘制的任何内容都不是对象。

如果你想假装它们是对象(比如在一个矩形或一条线上移动),那么你需要跟踪所有内容并进行所有的命中测试并重新绘画。< / p>

我开始编写一个gentle introduction article来制作你可以选择并拖动的矩形。给那个读。