绘制多个填充图像内容的圆圈

时间:2011-04-12 11:43:16

标签: html5-canvas

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

我已找到绘制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>

1 个答案:

答案 0 :(得分:3)

我可以用yor代码看到两个问题:

第一个是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/

相关问题