清除画布html5中的上下文

时间:2014-11-25 20:19:50

标签: javascript jquery html5 canvas

我想在画布中绘制照片,并允许用户在其上拖动一个圆圈。我能够做到。问题是当我清除上下文时,我绘制的图像消失了(见这里:http://jsfiddle.net/wL0ossth/)如果不清除上下文,整个图像都被彩色圆圈填满(见这里:{{3 }})。一些代码:

<canvas id="canvas" width=300 height=300></canvas>
    <img id="scream" src="http://i10.dainikbhaskar.com/thumbnail/655x588/web2images/www.bhaskar.com/2014/11/25/2324_bus.jpg" alt="The Scream" width="220" height="277">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

JavaScript:&#39; http://jsfiddle.net/wL0ossth/1/

var c=document.getElementById("canvas");
     var img=document.getElementById("scream");  
     var ctx=c.getContext("2d");
     ctx.drawImage(img,10,10); 
 canvas.addEventListener('mousemove', followMouse, false);  

function findOffset(obj) {
    var curX = curY = 0;
    if (obj.offsetParent) {
        do {
            curX += obj.offsetLeft;
            curY += obj.offsetTop;
        } while (obj = obj.offsetParent);
    return {x:curX,y:curY};
    }
}

function followMouse(e){


    ctx.beginPath();
    var offset = findOffset(canvas);   //get the offset of the canvas relative to the page

    var posX = e.pageX - offset.x;     //find the x position of the mouse
    var posY = e.pageY - offset.y;     //find the y position of the mouse

    ctx.arc(posX,posY,50,0,Math.PI*2,false);   //draw a circle
    ctx.fill(); 
}

编辑:我想让圈子随着清晰的上下文移动以及我画的图像。简而言之,在http://jsfiddle.net/wL0ossth/1/

中绘制的圆圈中没有留下黑色痕迹

1 个答案:

答案 0 :(得分:1)

我认为你想要这样的东西(虽然我不确定,除非你澄清一下你的帖子):

&#13;
&#13;
$(document).ready(function() {

  var c = document.getElementById("canvas");
  var img = document.getElementById("scream");
  var ctx = c.getContext("2d");
  canvas.addEventListener('mousemove', followMouse, false);

  function findOffset(obj) {
    var curX = 0,
        curY = 0;
    if (obj.offsetParent) {
      do {
        curX += obj.offsetLeft;
        curY += obj.offsetTop;
      } while (obj = obj.offsetParent);
      return {
        x: curX,
        y: curY
      };
    }
  }

  function followMouse(e) {

    ctx.clearRect(0, 0, 300, 300);
    ctx.drawImage(img, 10, 10); // Notice I moved the image down to here
    ctx.beginPath();
    var offset = findOffset(canvas); //get the offset of the canvas relative to the page

    var posX = e.pageX - offset.x; //find the x position of the mouse
    var posY = e.pageY - offset.y; //find the y position of the mouse

    ctx.arc(posX, posY, 50, 0, Math.PI * 2, false); //draw a circle
    ctx.fill();
  }

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width=300 height=300></canvas>
<img id="scream" src="http://i10.dainikbhaskar.com/thumbnail/655x588/web2images/www.bhaskar.com/2014/11/25/2324_bus.jpg" alt="The Scream" width="220" height="277">
&#13;
&#13;
&#13;

您需要做的是将drawImage(img)放在clearRect之后。这样,每次清除画布时,都会再次绘制图像。