'Texturing raycaster

I am making a raycaster in JavaScript using the Canvas API, everything has worked so far, except for a few things. When I try to render textures, it only renders it through half of the tile. My code to render them is as follows: (r.x2 and r.y2 are the collision points of the ray)

textureOffset = r.axis == 'x' ? (r.x2 % tilesize) : (r.y2 % tilesize)
            tileTexture = new Image()
            tileTexture.src = getTileTex(r.tileVal).customTexture.src
            customTex = getTileTex(r.tileVal).customTexture;

            ctx.drawImage(tileTexture,
                //original image coords
                (textureOffset*(customTex.imageSize/segmentWidth)) + customTex.offX, customTex.offY, customTex.imageSize/segmentWidth, customTex.imageSize,
                //drawing image coords
                i*segmentWidth, h/2 - height/2, segmentWidth, height
            )

This code produces this: raycaster1

There are also some glitches like flickering and fisheye, but I don't think those are related.

You can view the source code here, or play the demo here. Thanks in advance, (and sorry for the bad question, I really don't know how to phrase this)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source