简体   繁体   English

形状未绘制到 canvas javascript

[英]shape not being drawn to the canvas javascript

I am making a game engine called Forge.js.我正在制作一个名为 Forge.js 的游戏引擎。 I have a Polygon method in a Entity class and it is not drawing the shapes.我在实体 class 中有一个多边形方法,它没有绘制形状。 It loops through points and draws a line to each of the points.它循环通过点并在每个点上画一条线。 The lines however aren't being drawn.然而,这些线没有被绘制出来。 help plz帮助请

polygon method:多边形法:

_polygon(points){
        const local_ctx = new Path2D()

        this.ctx.beginPath()

        var j = 3

        local_ctx.moveTo(points[0], points[1])
        
        for (var i=0; i<=points.length; i++){
            local_ctx.lineTo(points[i+2], points[i+j])

            j += 2

        }

        this.ctx.fillStyle = constants.COLORS.black
        this.ctx.fill()

    }

As has been said in the comments, you need to pass the Path2D object to fill() in order for the context to draw it.正如评论中所说,您需要将 Path2D object 传递给fill()以便上下文绘制它。
But this isn't the only issue with your code.但这不是您的代码的唯一问题。

Your for loop probably doesn't do what you expected:您的 for 循环可能没有达到您的预期:

 // Rewrote in order to log the indexes that are beign used in the loop var j = 3 console.log(0, 1) for (var i=0; i<=10; i++){ console.log(i+2, i+j) j += 2 }

You can actually simplify this loop a lot by taking advantage of the fact that an empty subpath doesn't require an initial moveTo call.通过利用空子路径不需要初始moveTo调用这一事实,您实际上可以大大简化此循环。 lineTo(x, y) gets automatically converted to moveTo(x, y) if your path is empty.如果您的路径为空lineTo(x, y)会自动转换为moveTo(x, y)
So we can treat all our points the same, all in a single for loop that only increments our index by 2.因此,我们可以将所有点都视为相同,所有这些都在一个 for 循环中,只会将我们的索引增加 2。

 const constants = { COLORS: { BLACK: "#000" } }; const obj = { ctx: document.createElement("canvas").getContext("2d"), _polygon(points){ const local_ctx = new Path2D() // Since we're using a Path2D object we don't need to do anything // on the context's subpath // this.ctx.beginPath() for (var i=0; i<=points.length; i+=2){ local_ctx.lineTo(points[i], points[i+1]) } this.ctx.fillStyle = constants.COLORS.black this.ctx.fill(local_ctx) // fill the context using the Path2D object } }; document.body.append(obj.ctx.canvas); obj._polygon([13, 13, 13, 50, 50, 50]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM