猿问

canvas里我想给制作的多个图形加图片背景,怎么实现

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


慕仙0369855
浏览 3667回答 0
0回答
随时随地看视频慕课网APP

相关分类

Html5
我要回答