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

私があなたのコードで見ることができる2つの問題があります:

1 つ目は、start_drawing実行ごとにキャンバスをクリアすることです。したがって、マウスをクリックするたびに(マウスクリックstart_drawingで呼び出されると思います)、円が描画されますが、キャンバスはその前にクリアされます。

もう 1 つは、作成するクリッピング領域ごとにBeginPathとを呼び出す必要があることです。closePathしたがって、コードは次のようになります。

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 に答える