0

我有一个问题,我正在画布上实现裁剪自定义矩形我在 Javascript 中创建了一个函数,当调用裁剪函数时,在现有画布上创建一个子项,然后使用 JQuery 侦听器绘制矩形。创建子节点正确,而听众不工作,他们没有得到事件。这是我的代码:

var dragging = false;
var xstart = 0;
var ystart = 0;
var width = 0;
var height = 0;
var ctxotmp = null;
var ctxtmp = null; 
var canvastmp = null;
var mycanvas = null;
function draw() {
 ctxtmp.fillRect(xstart, ystart, width, height);
}

function init() {
    mycanvas = $('#mycanvas')[0];
   // create temp canvas
    canvastmp = document.createElement('canvas');
    canvastmp.id = "mycanvastmp";
    canvastmp.width = mycanvas.width;
    canvastmp.height = mycanvas.height;
    mycanvas.parentNode.appendChild(canvastmp);
    $("#mycanvastmp").css({position:"absolute",top:$("#mycanvas").css("top"),left:$("#mycanvas").css("left")});
    canvastmp = $('#mycanvastmp')[0];
   ctxtmp = canvastmp.getContext('2d');
   ctxtmp.lineWidth = 1;
   ctxtmp.fillStyle = "rgba(0, 0, 0, 0.5)";
}
//listener
$('#mycanvastmp').mousedown(function(e) {
    var xoffs = $(this).offset().left;
    var yoffs = $(this).offset().top;
    xstart = e.pageX - xoffs;
    ystart = e.pageY - yoffs;
    dragging = true;
  });

  $('#mycanvastmp').mousemove(function(e) {
    if(dragging) {
      var xoffs = $(this).offset().left;
      var yoffs = $(this).offset().top;
      width = e.pageX - xoffs - xstart;
      height = e.pageY - yoffs - ystart;
      ctxtmp.clearRect(0, 0, $(this).width(), $(this).height());
      draw();
    }
  });

  $('#mycanvastmp').mouseup(function() {
    dragging=false;
    alert('The rectangle for crop (x, y, width, height): ' + xstart + ', ' + ystart + ', ' + width + ', ' + height);
  });

有人可以帮助我吗?

4

2 回答 2

0

您需要使用.on on 方法将事件绑定到动态创建的对象。当您的页面最初加载并且 dom 触发时,它看不到tempCanvas,因此最初不会附加它们。

//listener
$('body').on('mousedown' ,'#mycanvastmp', function(e) {

    var xoffs = $(this).offset().left;
    var yoffs = $(this).offset().top;
    xstart = e.pageX - xoffs;
    ystart = e.pageY - yoffs;
    dragging = true;
  });

  $('body').on('mousemove' ,'#mycanvastmp', function(e) {
    if(dragging) {
      var xoffs = $(this).offset().left;
      var yoffs = $(this).offset().top;
      width = e.pageX - xoffs - xstart;
      height = e.pageY - yoffs - ystart;
      ctxtmp.clearRect(0, 0, $(this).width(), $(this).height());
      draw();
    }
  });

 $('body').on('mouseup' ,'#mycanvastmp', function(e) {
    dragging=false;
    alert('The rectangle for crop (x, y, width, height): ' + xstart + ', ' + ystart + ', ' + width + ', ' + height);
  });

init();

现场演示

于 2012-06-14T19:31:05.350 回答
0

看起来您在创建临时画布之前附加了事件。init()在将临时画布添加到 DOM 后附加函数中的事件或使用.delegate().on()

$("#mycanvas").on("mouseup", "#mycanvastmp", function() {
    //...
});
于 2012-06-14T19:32:09.767 回答