javascript - 如何找到 Canvas 中有多少个单位?

标签 javascript html css canvas

我有下面列出的代码。代码在https://omegalords.ga/test.world.html .我希望该元素不会超出 Canvas 。如何找到 Canvas 中有多少个单位?我知道控制台中的其他错误。我特别需要 Canvas 的尺寸来引用放置在 Canvas 上的元素。代码的重点是创建交互的狼和鹿。问题是我需要确保 2 不会离开 Canvas 。

<script src=../script/algebra-0.2.6.min.js></script>
<canvas id="myCanvas" style="width:100%; height:100%;">

</canvas>
<script>
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    console.log(document.body.style)
    var findDis = function(x1,y1,x2,y2){
        //Finds distance rounded to the nearest 1000th
        return Math.trunc(((Math.sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2)))*1000))/1000
    }
    var findIntersections = function(b,a,m,r){
        var Fraction = algebra.Fraction;
        var Expression = algebra.Expression;
        var Equation = algebra.Equation;
        var coords = {
            l:[],
            g:[]
        }
        //b^2 - 2bx + x^2 - 2bm^2x + b^2m^2 - r^2
        var sl = algebra.parse(Math.pow(b,2)+" - "+2*b+"x + x^2 + "+Math.pow(m,2)+"x^2 -" + 2 * b * Math.pow(m,2) + "* x + " + Math.pow(b,2) * Math.pow(m,2) + " - " + Math.pow(r,2));
        var sr = algebra.parse("0")
        var eq = new Equation(sl, sr);
        //Solves for x rounded to the nearest 1000
        coords.l.push(Math.trunc((eq.solveFor("x")[0]*1000))/1000);
        coords.g.push(Math.trunc((eq.solveFor("x")[1]*1000))/1000);
        //Solves for y
            coords.l.push(Math.trunc((eq.solveFor("x")[0] * m + a - (b * m))*1000)/1000);
            coords.g.push(Math.trunc((eq.solveFor("x")[1] * m + a - (b * m))*1000)/1000);
        return JSON.stringify(coords);
    }
    var findSlope = function(x1,y1,x2,y2){
        //Finds Slope rounded to the nearest 1000th
        return Math.trunc(((y1-y2)/(x1-x2))*1000)/1000;
    }
    var getRandomInt = function(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min)) + min; 
    }
    var wolves = [];
    var deers = [];
    var animal = function(x,y){
        this.age = 0 
        this.strength = 0;
        this.x = x;
        this.y = y;
        this.hp = 100;
        this.size = 10;
        this.hunger = 0;
    }
    animal.prototype.move = function(){
        this.nearbyPredators = [];
        this.nearbyPrey = [];
        for(var j = 0;j<this.predatorTypes.length;j++){
            for(var i = 0;i < this.predatorTypes[j].length;i++){
                if(findDis(this.predatorTypes[j][i].x,this.predatorTypes[j][i].y,this.x,this.y) < 40){
                    this.nearbyPredators.push(this.predatorTypes[j][i]);
                }else{
                    console.log(findDis(this.predatorTypes[j][i].x,this.this.predatorTypes[j][i].y,this.x,this.y))
                }
            }
        }
        //finds all nearby prey
        for(var j = 0;j<this.preyTypes.length;j++){
            for(var i = 0;i < this.preyTypes[j].length;i++){
                if(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y) < 40){
                    this.nearbyPrey.push(this.preyTypes[j][i]);
                }else{
                    console.log(findDis(this.preyTypes[j][i].x,this.preyTypes[j][i].y,this.x,this.y))
                }
            }
        }
        if(this.nearbyPredators.length == 0){
            //If there are no nearby prey, move randomly
            if(this.nearbyPrey.length === 0){
                var tx = this.x + getRandomInt(-8,9);
                var ty = this.y + getRandomInt(-9,8);
                while(!(tx > (0 + this.size)) && !(ty > (0 + this.size)) && !(tx < (canvas.length - this.size)) && !(ty < (canvas.height - this.size))){
                    tx = this.x + getRandomInt(-8,9);
                    ty = this.y + getRandomInt(-9,8);
                }
                this.x = tx
                this.y = ty
            //If there is only one nearby prey, move towards it
            }else if(this.nearbyPrey.length === 1){
                this.nearestPrey = this.nearbyPrey[0]
                var tempDis = findDis(this.x,this.y,this.nearestPrey.x,this.nearestPrey.y);
                if(tempDis < 2*this.nearestPrey.size){
                    this.bite(this.nearestPrey)
                }else {
                    var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y);
                    var coords = JSON.parse(findIntersections(this.x,this.y,slope,0.125));
                    var ldis = findDis(this.x,this.y,coords.l[0],coords.l[1]);
                    var gdis = findDis(this.x,this.y,coords.g[0],coords.g[1]);
                    if(ldis > gdis){
                        this.x = coords.l[0]
                        this.y = coords.l[1]
                    }else {
                        this.x = coords.g[0]
                        this.y = coords.g[1]
                    }
                }
            //If there is more than 1, find the nearest prey and move towards it
            }else {
                for(var i = 0; i < this.nearbyPrey.length; i++){
                    this.tempDis = getDis(this.x,this.y,this.nearbyPrey[i].x,this.nearbyPrey[i].y)
                    if(typeof this.nearestPrey == 'undefined'){
                    this.nearestPrey = {
                        prey:this.nearbyPrey[i],
                        distance:this.tempDis
                    }
                        this.tempDis = undefined
                    }else {
                        if(this.tempDis > this.nearestPrey.distance){
                            this.nearestPrey = {
                                prey:this.nearbyPrey[i],
                                distance:this.tempDis
                            }
                        }
                    }
                }
                var slope = findSlope(this.nearestPrey.x,this.nearestPrey.y,this.x,this.y)
                var coords = JSON.parse(findIntersections(this.nearestPrey.x,this.nearestPrey.y,slope,0.25));
                var ldis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.l[0],coords.l[1]);
                var gdis = findDis(this.nearestPrey.x,this.nearestPrey.y,coords.g[0],coords.g[1]);
                if(ldis > gdis){
                    this.x = coords.l[0]
                    this.y = coords.l[1]
                }else {
                    this.x = coords.g[0]
                    this.y = coords.g[1]
                }
            }
        }else {

        }
    }
    var grass = function(){

    }
    var deer = function(x,y){
        animal.call(this,x,y)
        deers.push(this);
        this.preyTypes = [grass];
        this.predatorTypes = [wolves];
    }
    var wolf = function(x,y){
        animal.call(this,x,y)
        wolves.push(this);
        this.predatorTypes = [];
        this.preyTypes = [deers]
    }
    deer.prototype = Object.create(animal.prototype);
    wolf.prototype = Object.create(animal.prototype);
    wolf.prototype.bite = function(prey){
        prey.hp -= this.strength;
        if(prey.hp < 0){
            prey.die()
        }
        this.hunger += 40/100
        console.log(this.hunger);
        console.log(prey.hp)
    }
    new wolf(100,100)
    new deer(50,50);
    var init = function(){
        ctx.translate(0.5, 0.5);
        ctx.lineWidth = .5
        window.setInterval(draw,250);
    }
    var draw = function(){
        ctx.clearRect(0,0,canvas.width,canvas.height)
        wolves[0].move();
        for(var i=0;i<wolves.length;i++){
            ctx.beginPath()
            ctx.arc(wolves[i].x,wolves[i].y,10,0,2*Math.PI);
            ctx.stroke();
        }
        for(var i=0; i<deers.length;i++){
            ctx.beginPath();
            ctx.arc(deers[i].x,deers[i].y,10,0,2*Math.PI);
            ctx.stroke();
        }
    }
    init()
</script>

最佳答案

var canvasHeight = canvas.clientHeight;
var canvasWidth = canvas.clientWidth;

请注意,这也将包括任何填充,但默认情况下, Canvas 没有填充。

来源:

https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight

https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth

关于javascript - 如何找到 Canvas 中有多少个单位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50516517/

相关文章:

php - 获取订单项 woocommerce 订单

html - 如何使输入栏的高度取决于文本的数量

html - 无输入时边框颜色变化

javascript - 选择每个单词并给它另一种颜色

css - 根据类名选择第一个元素 css

javascript - React - Google Map 组件在重新渲染后不会更改 map

javascript - Angular JS 在 plunker 中不起作用

javascript - .js 文件中的特殊字符最初未正确显示

javascript - 切换 Chrome 标签页并每 5 秒刷新一次 - javascript

javascript - 如何从另一个页面更改一个页面的 html 代码?