How can I create a perspective effect within a canvas?

Viewed 511

I know how to create a perspective effect in vanilla CSS, but how can I create this effect in a canvas?

.scene {
  width: 200px;
  height: 200px;
  border: 2px solid black;
  margin: 40px;
}

.panel {
  width: 100%;
  height: 100%;
  background: red;
  /* perspective function in transform property */
  transform: perspective(600px) rotateY(45deg);
}
<div class="scene">
  <div class="panel"></div>
</div>

I tried the setTransform() method without sucess.

function drawScene(margin, size) {
    ctx.strokeStyle = "black";
    ctx.strokeRect(margin, margin, size, size);
}

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

var margin = 100;
var size = 200;

drawScene(margin, size)

ctx.setTransform(1, -0.1, 0, 1, -10, 0);
//ctx.rotate(1 * Math.PI / 180); how to rotateY

ctx.fillStyle = "red";
ctx.fillRect(margin, margin, size, size);

ctx.fillStyle = 'black';
ctx.font = "48px Courier";
ctx.fillText("hello", margin, size);
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;"></canvas>

I tried both solution from HTML Canvas: Rotate the Image 3D effect but none nailed it. The perspective effet isnt here.

1 Answers

You need create a path by points matrix (x1, y1; x2, y2; x3, y3; x4, y4). Apply a transform matrix in your point matrix. After, print on canvas with path.

1: You need study by tranformation matrix (http://docdingle.com/teaching/cs545/presents/p12b_cs545_WarpsP2.pdf)

2:In Summary you have a transformation' matrix to translading, space, rotate or apply perspective deformation:

    //this is a tranformation matrix to percpective deformation A and B are values that apply deformation
    matrix_tranf = [ [1, 0 ,0] ,  [0,1,0] , [ A, B, 1] ];

In my code I left any examples


for(let i = 0; i < 4; i++){
    //u
    x1 = matrix[i][0]
    //v
    y1 = matrix[i][1]
    w = matrix_tranf[2][0] * x1 + matrix_tranf[2][1] * y1 + 1;
    v = [  ( x1 / w ) , ( y1 / w )  ];
    matrix[i] = v;
}

Look https://codepen.io/Luis4raujo/pen/wvoqEwg

If this answer help you, check as correct or voteup!

Related