需要帮助将图像放入javascript snake吗

需要帮助将图像放入javascript snake吗,javascript,html,image,Javascript,Html,Image,我刚开始写脚本,正在做信息学项目,我需要帮助将图像放到背景中: <canvas id="gc" width="2137" height="2137"></canvas> <script> window.onload=function() { canv=document.getElementById("gc"); ctx=canv.getContext("2d"); document.addEventListener("keydown"

我刚开始写脚本,正在做信息学项目,我需要帮助将图像放到背景中:

<canvas id="gc" width="2137" height="2137"></canvas>

<script>
window.onload=function() {
    canv=document.getElementById("gc");
    ctx=canv.getContext("2d");
    document.addEventListener("keydown",keyPush);
    setInterval(game,1000/15);
}
px=py=5;
gs=tc=47;
ax=ay=25;
xv=yv=0;
trail=[];
tail = 5;
function game() {
    px+=xv;
    py+=yv;
    if(px<0) {
        px= tc-1;
    }
    if(px>tc-1) {
        px= 0;
    }
    if(py<0) {
        py= tc-1;
    }
    if(py>tc-1) {
        py= 0;
    }
    ctx.fillStyle="black";
    ctx.fillRect(0,0,canv.width,canv.height);

    ctx.fillStyle="lime";
    for(var i=0;i<trail.length;i++) {
        ctx.fillRect(trail[i].x*gs,trail[i].y*gs,gs-2,gs-2);
        if(trail[i].x==px && trail[i].y==py) {
            tail = 5;
        }
    }
    trail.push({x:px,y:py});
    while(trail.length>tail) {
    trail.shift();
    }

    if(ax==px && ay==py) {
        tail++;
        ax=Math.floor(Math.random()*tc);
        ay=Math.floor(Math.random()*tc);
    }
    ctx.fillStyle="red";
    ctx.fillRect(ax*gs,ay*gs,gs-2,gs-2);
}
function keyPush(evt) {
    switch(evt.keyCode) {
        case 37:
            xv=-1;yv=0;
            break;
        case 38:
            xv=0;yv=-1;
            break;
        case 39:
            xv=1;yv=0;
            break;
        case 40:
            xv=0;yv=1;
            break;
    }
}
</script>

我试着使用所有的东西,但都没用。

为什么不使用css将背景图像设置到画布上呢?下面是一个工作示例

#gc{
背景图像:url('http://placehold.it/300x300?text=snake+背景';
}

如果您需要将图像放入画布游戏,请将预加载的图像元素放入每个循环中,背景清除内/后:

var-img;
window.onload=function(){
canv=document.getElementById(“gc”);
ctx=canv.getContext(“2d”);
文件。添加了文本列表(“按键向下”,按键推动);
img=新图像();
img.onload=函数(){
设定间隔(游戏,1000/15);
};
img.src=http://loremflickr.com/g/2137/2137/cat';
}
px=py=5;
gs=tc=47;
ax=ay=25;
xv=yv=0;
trail=[];
尾=5;
函数游戏(){
px+=xv;
py+=yv;
如果(pxtc-1){
px=0;
}
if(pytc-1){
py=0;
}
ctx.fillStyle=“黑色”;
ctx.fillRect(0,0,扫描宽度,扫描高度);
ctx.drawImage(图像,0,0,扫描宽度,扫描高度);
ctx.fillStyle=“石灰”;
对于(var i=0;itail){
trail.shift();
}
如果(ax==px&&ay==py){
tail++;
ax=数学地板(数学随机()*tc);
ay=Math.floor(Math.random()*tc);
}
ctx.fillStyle=“红色”;
ctx.fillRect(ax*gs、ay*gs、gs-2、gs-2);
}
功能键推送(evt){
开关(evt.keyCode){
案例37:
xv=-1;yv=0;
打破
案例38:
xv=0;yv=-1;
打破
案例39:
xv=1;yv=0;
打破
案例40:
xv=0;yv=1;
打破
}
}

您忘记了背景中的“d;”请给它一个更好的标题
ctx.fillStyle="black";
    ctx.fillRect(0,0,canv.width,canv.height);