HTML5 Canvas Ghosting Issue

时间:2014-10-13 15:08:29

标签: html5 canvas

当用户将光标拖过屏幕时,会绘制一个方形画布。我的问题是画布是“重影”。我认为使用redraw()或clearrect()可以解决这个问题,但我不确定如何在这种情况下实现这些功能。感谢。

drawSquare = true;
//DRAG TO CREATE RECTANGLE

if(drawSquare == true){
    $(document).mousedown(function(e) {
        dragShape = true;
        posYdown = e.pageY;
        posXdown = e.pageX;
    });
        $(document).mousemove(function(e) {
            if(dragShape == true) {
                var c=document.getElementById("canvas1");
                var ctx=c.getContext("2d");
                ctx.fillStyle = "black";
                ctx.fillRect(posXdown ,posYdown ,e.pageX - posXdown ,e.pageY - posYdown);           
            }
        });
            $(document).mouseup(function() {
                dragShape = false;
            });
}

1 个答案:

答案 0 :(得分:0)

是的,您需要context.clearRect删除之前绘制的像素,否则您将拥有幽灵残骸。

这是您的代码的重构版本:

提示:

  • 在绘制新矩形之前清除画布。
  • 只需在应用开始时获取对画布和上下文的引用。
  • 通过画布的偏移X,Y调整鼠标位置(以防您稍后在页面上重新定位画布)。

祝你学习顺利!



var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;

var dragShape=false;
var posXdown,posYdown;



function handleMouseDown(e){
  e.preventDefault();
  e.stopPropagation();

  posXdown=parseInt(e.clientX-offsetX);
  posYdown=parseInt(e.clientY-offsetY);

  dragShape = true;
}

function handleMouseUp(e){
  e.preventDefault();
  e.stopPropagation();
  dragShape = false;
}

function handleMouseMove(e){
  if(!dragShape){return;}
  e.preventDefault();
  e.stopPropagation();

  var mouseX=parseInt(e.clientX-offsetX);
  var mouseY=parseInt(e.clientY-offsetY);

  var width=mouseX-posXdown;
  var height=mouseY-posYdown;
  ctx.clearRect(0,0,canvas.width,canvas.height);
  ctx.fillRect(posXdown,posYdown,width,height);           

}

$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseUp(e);});

body{ background-color: ivory; }
#canvas{border:1px solid red;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="canvas" width=300 height=300></canvas>
&#13;
&#13;
&#13;