<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; setInterval(function(){ for(var i=0;i<3;i++){ var bag={x:Math.random()*canvas.width,y:Math.random()*canvas.height} bags[i]=bag; } draw(); },1000) canvas.addEventListener("mouseup",change)}function change(event){ 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>
1 回答
慕仙0369855
TA贡献1条经验 获得超0个赞
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);
context.drawImage(img,bags[i].x,bags[i].y)
/* var pat=context.createPattern(img,"no-repeat")
context.fillStyle=pat;
context.fill();*/
if(context.isPointInPath(x,y)){
console.log(i)
context.fillStyle="red";
context.fill();
}
}
}
我用这样的解决方法,不知道还有没其他更合适的
- 1 回答
- 0 关注
- 1368 浏览
添加回答
举报
0/150
提交
取消