<script type="text/javascript">
var canvas=document.getElementById("myCanvas");
var context=canvas.getContext("2d");
var bags=[]
var img=new Image();
img.src="img/redbag.png";
window.onload=function(){
canvas.width=800;
canvas.height=800;
for(var i=0;i<3;i++){
var bag={x:Math.random()*canvas.width,y:Math.random()*canvas.height}
bags[i]=bag;
}
draw();
canvas.addEventListener("mouseup",change)
}
function change(){
var x=event.clientX-canvas.getBoundingClientRect().left;
var y=event.clientY-canvas.getBoundingClientRect().top;
draw(x,y);
}
function draw(x,y){
context.clearRect(0,0,canvas.width,canvas.height)
for(var i=0;i<bags.length;i++){
context.beginPath();
context.rect(bags[i].x,bags[i].y,60,60);
var pat=context.createPattern(img,"repeat")
context.fillStyle=pat;
context.fill();
if(context.isPointInPath(x,y)){
context.fillStyle="red";
context.fill();
}
}
}
</script>
相关分类