Mode7-like perspective transform in canvas?

前端 未结 2 1260
星月不相逢
星月不相逢 2020-12-24 08:40

I\'m making a canvas-based game engine and am wondering if anyone has any good info on how to achieve an overhead view perspective. What I\'m looking for is somewhere halfwa

相关标签:
2条回答
  • 2020-12-24 09:12

    What you're talking about is something that can be done simply with any 3D api. However since you've decided to try to stick to 2D canvas, you have to do everything in the 2D world which means working with rectangles, rotation, scaling, skewing, etc. Also know as affine transformations as mentioned the other answer.

    What you want to do is possible, but since you want to use 2D you have to think in terms of 2D functions.

    1. Generate your initial image.
    2. Add a slice from the bottom of the original image to the bottom of the canvas, very slightly positioned to the left so the center of the image matches up with the center of the current canvas.
    3. Very slightly increase the scale of the entire image
    4. Repeat until you get to the top of the image.

    The Pseudo code would look like this...

    imgA = document.getElementById('source');
    
    // grab image slices from bottom to top of image
    for (var ix=height-slice_height;ix>=0;ix-=slice_height)
    {
    
        // move a section of the source image to the target canvas
        ctx.drawImage(imgA, 0,ix,width,slice_height, 
             0-half_slice_width_increase,width,slice_height);
        // stretch the whole canvas
        ctx.scale(scale_ratio, 1);
    }
    

    This will take lots of tweaking, but that is the general solution.

    • scale_ratio will be a number slightly larger, but very close to 1.
    • ctx is the standard canvas 2D context
    • half_slice_width_increase is the 1/2 the amount the canvas will grow when scaled by the scale ratio. This keeps the scaled image centered.

    To look correct you would want to transform the background tiles first before you add the icon overlays.

    0 讨论(0)
  • 2020-12-24 09:25

    if i understand you right, you just want a simple trapeze transformation. if so, maybe this or this link helps you out. for images that aren't centered it would just be an additional rhomboid tranformation, wich is easily possible with canvas, as far as i know.

    0 讨论(0)
提交回复
热议问题