HTML Canvas:如何设置边框限制? [英] HTML Canvas: How Do I Set Border Restrictions?

查看:145
本文介绍了HTML Canvas:如何设置边框限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个程序,可以使用 w a s d 键。我很难弄清楚如何让这个块不超出画布的边界,并且仅限于留在其中。

I have created a program that can move a rectangular block up, down, right, and left within a canvas using the w, a, s and d keys. I am having difficulty figuring out how to have the block not go beyond the borders of the canvas and be restricted only to stay within it.

这是我的代码的一部分对于画布:

Here is the part of my code for the canvas:

<html>
<head>
    <script>
    var positionX=0;
    var positionY=0;

    window.addEventListener("keydown", onKeyPress, true);

    function draw(){
        var canvas=document.getElementById("canvas_c");
        var context=canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        context.fillStyle="green";
        context.fillRect(positionX, positionY, 100, 100);
        context.strokeStyle = 'black';
        context.stroke();
    }
    function onKeyPress(e){ 
        if (e.keyCode==87){
            positionY-=15;
        }
        if (e.keyCode==83){
            positionY+=15;
        }
        if (e.keyCode==68){
            positionX+=50;
        }
        if (e.keyCode==65){
            positionX-=50;
        }
        draw();
        }
    </script>
</head>
<body>
    <div id="firstDiv">
        <canvas id="canvas_c" width="1000" height="500" style="border: 1px solid black;"> </canvas>

    </div> 
</body> 

推荐答案

这里是用于基本边界运动函数的伪代码:

Here is pseudo-code for the basic boundary respecting movement functions:

// assuming this block object: var block={x:10,y:10,width:20,y:20};
function goLeft(){  if(block.x>0){block.x--;} }
function goUp(){    if(block.y>0){block.y--;} }
function goRight(){ if(block.x<(canvas.width-block.width)){block.x++;} }
function goDown(){  if(block.y<(canvas.height-block.height)){block.y++;} }

:这里的代码基于您添加到您的问题的代码]

警告:未经测试的代码...可能需要调整! : - )

// save the canvas width & height at the top of the app
var canvas=document.getElementById("canvas1");
var cw=canvas.width;
var ch=canvas.height;

function onKeyPress(e){
    if (e.keyCode==87){
        positionY=Math.max(0,positionY-15);
    }
    if (e.keyCode==83){
        positionY=Math.min(cw-100,positionY+15);
    }
    if (e.keyCode==68){
        positionX=Math.min(ch-100,positionX+50);
    }
    if (e.keyCode==65){
        positionX=Math.max(0,positionX-50);
    }
    draw();
}

这篇关于HTML Canvas:如何设置边框限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆