0

我正在尝试在充满图像部分的画布上绘制圆圈。想象一下单击白色画布,用户单击的位置会显示照片的一部分。

我找到了绘制 1 个圆圈的方法,但无法成功使用它来绘制多个圆圈。如果我用其他坐标重复该动作,则绘图不会发生。

function start_drawing(){
    ctx.beginPath();
    ctx.fillStyle = "rgb(255,255,255)";
    ctx.fillRect(0,0,canvas.width,canvas.height);//fill the background. color is default black
    ctx.arc(mouse.x,mouse.y,45,0,6.28,false);//draw the circle
    ctx.arc(mouse.x+100,mouse.y+100,45,0,6.28,false);
    ctx.clip();//call the clip method so the next render is clipped in last path
    ctx.drawImage(img,0,0); 
    ctx.closePath();
}

关于如何实现这一点的任何想法?谢谢你。


稍后编辑(使用的整个确切代码)

<!DOCTYPE HTML>
<html>
<head>
<script>

window.onload=function(){  

var canvas = document.getElementById('myCanvas');  
var ctx=canvas.getContext('2d');  

var mouse={x:0,y:0} //make an object to hold mouse position

canvas.onmousemove=function(e){mouse={x:e.pageX-this.offsetLeft,y:e.pageY-this.offsetTop};} //update the mouse when the canvas is moved over

var img=new Image();

img.src="bmw_gina.jpg";

setInterval( start_drawing ,100);// set the animation into motion

 ctx.beginPath();
 ctx.fillStyle = "rgb(255,255,255)";
 ctx.fillRect(0,0,canvas.width,canvas.height);//fill the background. color is default black
  ctx.closePath();

function start_drawing(){
 //ctx.save();
 ctx.beginPath();

                     ctx.arc(mouse.x,mouse.y,45,0,6.28,false);//draw the circle
                     ctx.clip();//call the clip method so the next render is clipped in last path
                     ctx.drawImage(img,0,0);  
 ctx.closePath();
 //ctx.restore();
}

}

</script>
</head>
<body>
    <canvas id="myCanvas" width="1003" height="914"></canvas>

</body>
</html>
4

1 回答 1

3

我可以看到您的代码有两个问题:

第一个是start_drawing每次执行都清除画布。因此,对于每次鼠标单击(我假设start_drawing在鼠标单击时调用),都会绘制圆圈,但在此之前清除画布。

另一个是您需要为要创建的每个剪辑区域调用BeginPathclosePath。所以你的代码应该是这样的:

function start_drawing(){ 

    ctx.fillStyle = "rgb(255,255,255)"; 
    ctx.fillRect(0,0,canvas.width,canvas.height);//fill the background. color is default black
    ctx.beginPath(); 
    ctx.arc(mouse.x,mouse.y,45,0,6.28,false);//draw the circle
    ctx.clip();//call the clip method so the next render is clipped in last path 
    ctx.closePath(); 
    ctx.drawImage(img,0,0); 
    ctx.beginPath(); 
    ctx.arc(mouse.x+100,mouse.y+100,45,0,6.28,false);
    ctx.clip();//call the clip method so the next render is clipped in last path 
    ctx.closePath();  
    ctx.drawImage(img2,0,0); 

}

更新

显然,重置剪辑区域的技巧是重置画布。这可以通过重新设置它的宽度来实现。

你去:http: //jsfiddle.net/qCg9N/5/

于 2011-04-13T10:43:01.957 回答