0

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

谢谢

4

1 回答 1

0

这个答案被打破了。

您想在不触及底层绘画的情况下绘制线条并移动它们。在过去的好日子里,使用的方法是在绘图顶部使用 xor 组合进行绘制,并在同一位置以相同的方式绘制相同的图案(这里是线条)以将其从屏幕上移除,再次不触摸真正的绘画。

我试图用这个方法和下面的代码来测试它,但它似乎不起作用。希望对 canvas 和 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; 
})();

此外,根据浏览器的不同,合成也存在问题。

于 2012-12-15T10:30:59.887 回答