先上图片效果:
这里是代码,支持动态修改图片,通过选择文件更图片链接形式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
let c=null;
let ctx;
let star=[];
let image;
function createStar(){
for(let i=0;i<200;i++){
star.push({
x:Math.floor(Math.random()*1200-200),
y: Math.floor(Math.random()*1200-200),
})
}
}
function starS(p){
ctx.beginPath();
ctx.drawImage(image,p.x,p.y);
}
function starMove(){
for(let i=0;i<star.length;i++){
star[i].y+=3;
if(star[i].y>1000){
star[i].y=-200;
star[i].x=Math.floor(Math.random()*1200-200);
}
starS(star[i])
/* ctx.beginPath();
ctx.arc(star[i].x,star[i].y,3,0,Math.PI*2);
ctx.fill();
ctx.closePath();*/
}
}
function drawStar(){
}
window.onload=()=>{
c=document.getElementById('c');
ctx=c.getContext('2d');
ctx.fillStyle="rgba(88,209,255,0.65)"
createStar();
image=new Image();
image.src='水母3.png';
image.crossOrigin = "*";
setInterval(()=>{
ctx.clearRect(0,0,c.width,c.height);
starMove();
},10)
}
function SrcIn(e){
image=new Image();
image.src=e.target.value+'?v=' + Math.random();
image.crossOrigin = "*";
}
function fileIn(e){
let file = e.target.files[0];
image=new Image();
image.src=URL.createObjectURL(file);
image.crossOrigin = "*";
}
</script>
</head>
<body>
<canvas width="1000" height="1000" id="c" style="background-color: black;border:1px solid black;"></canvas>
<span>图片网址:</span>
<input onchange="SrcIn(event)"/>
<span>文件网址:</span>
<input type="file" accept="image/*" onchange="fileIn(event)"/>
</body>
</html>