Skip to content
Advertisement

Drawing the floor tiles with html5 canvas but it is note perfect.how can i make realistic using webgl

this is the imagedidn’t look like a floor tiles. Some transformation / rotate / Angle was missing. How to do perspective view with html5 canvas

here is the code

function drawPattern(img, size, rectY) {
    var roomImg = new Image();
        roomImg.src = './assets/room2.png';
        roomImg.onload = function() {
            ctx.drawImage(roomImg, 0, 0, canvas.width, canvas.height);
            ctx.restore();
        }
    var canvas = document.getElementById('canvas1');

        canvas.width = 1350;
        canvas.height = 600;

        var tempFloorCanvas = document.createElement("canvas");
        var tFloorCtx = tempFloorCanvas.getContext("2d");
        tempFloorCanvas.width = size;
        tempFloorCanvas.height = size;
        tFloorCtx.drawImage(floorimg, 0, 0, floorimg.width, floorimg.height, 0, 0, size, size);
        tFloorCtx.setTransform(1,1,-0.5,1,30,10);
        tFloorCtx.rotate(50);
        tFloorCtx.fill();
        var ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        

        ctx.fillStyle = ctx.createPattern(tempFloorCanvas, 'repeat');
        ctx.beginPath();

        ctx.rect(0,400,canvas.width, 400);
        ctx.closePath();
        ctx.fill();


        ctx.restore();

}

var floorimg = new Image();
        floorimg.src = './assets/tile5.jpg';
        floorimg.onload = function(){
            drawPattern(floorimg, 70, 0);
        }

If there is another solution to implement the feature or If there are third party plugins which can transform my canvas to some angle to be look like a floor of the room, then please let me know.

Advertisement

Answer

Out of the box the HTML5 CanvasRenderingContext2D API does not offer a way to do perspective projection. There are some full-blown third-party libraries, foremost Three.js that among other things let you do such kind of transformations.

However, if all you want to do is just perspectively distort an image it would be overkill to learn the Three.js API or even worse implementing it on your own using WebGL.

Luckily there is a tiny library called perspective.js.

Here’s an example:

let canvas = document.getElementById("canvas");
let image = new Image();
image.onload = function() {
  let ctx = canvas.getContext("2d");
  let p = new Perspective(ctx, image);

  p.draw([
    [30, 0],
    [canvas.width - 30, 0],
    [canvas.width, canvas.height],
    [0, canvas.height]
  ]);
}
image.src = "https://picsum.photos/id/1079/200/300";
canvas {
  border: gray solid 1px;
}
<script src="https://cdn.rawgit.com/wanadev/perspective.js/master/dist/perspective.min.js"></script>
<canvas id="canvas"></canvas>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement