猿问

想给绘制的多个矩形,添加完整的图片

<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>


慕仙0369855
浏览 1369回答 1
1回答

慕仙0369855

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(); } }} 我用这样的解决方法,不知道还有没其他更合适的
随时随地看视频慕课网APP

相关分类

CSS3
Html5
我要回答