如何在复杂的对象上绘画

时间:2012-12-14 22:38:37

标签: javascript html5-canvas

我的画布上有一个相当复杂的人物。 (~1000多边形)。所有这些的重新绘制时间约为1秒(非常慢)。现在我需要让用户移动该图并从鼠标位置下方显示垂直和水平线(十字线)。什么是最好的技术,只绘制那两行而不遍历所有多边形,并在每次鼠标移动时重绘所有内容。

THX

1 个答案:

答案 0 :(得分:0)

这个答案已经破解。

您想绘制线条并移动它们而不触及底层绘画。 在过去的好时光中,使用的方法是在图纸顶部使用xor合成进行绘制,并在同一位置以相同的方式绘制相同的图案(此处为线条)以将其从屏幕上移除,同样不会触碰真正的画作。

我尝试将此方法与下面的代码一起使用来测试它,但它似乎不起作用。希望有更好的画布和js知识的人会出现并解决问题。

function onmousemove(e){
  // firt run
  var tcanvas = document.getElementById("testCanvas");
  var tcontext = tcanvas.getContext("2d");
  var pos = {x : e.clientX, y : e.clientY, 
             w : tcanvas.width, h : tcanvas.height };
  var comp = tcontext.globalCompositeOperation;
  var paintline = function (p){
      tcontext.save();

      tcontext.lineWidth = 1;
      tcontext.globalCompositeOperation = 'xor';
      tcontext.fillStyle = "#000000";

      tcontext.moveTo(0,p.y);
      tcontext.lineTo(p.w,p.y);
      tcontext.moveTo(p.x,0);
      tcontext.lineTo(p.x,p.h);
      tcontext.stroke();

      tcontext.restore();
  };

  tcontext.save();
  paintline(pos);
  tcontext.restore();

  var next = function(e){
      var comp = tcontext.globalCompositeOperation;
      paintline(pos);
      pos = {x : e.clientX, y : e.clientY, 
             w : tcanvas.width, h : tcanvas.height };
      paintline(pos);
  };
  document.onmousemove = next;
}


(function draw_stuff(){
    // setup canvas
    var tcanvas = document.getElementById("testCanvas");
    var tcontext = tcanvas.getContext("2d");

    // draw square
    tcontext.fillStyle = "#FF3366";
    tcontext.fillRect(15,15,70,70);

    // set composite property
    tcontext.globalCompositeOperation = 'xor';

    // draw text
    tcontext.fillStyle="#0099FF";
    tcontext.font = "35px sans-serif";
    tcontext.fillText("test", 22, 25);
    // draw circle
    tcontext.fillStyle = "#0099FF";
    tcontext.beginPath();
    tcontext.arc(75,75,35,0,Math.PI*2,true);
    tcontext.fill();
    document.onmousemove = onmousemove; 
})();

此外,根据浏览器,合成存在问题。

相关问题