samizdatco / skia-canvas

A GPU-accelerated 2D graphics environment for Node.js
MIT License
1.7k stars 66 forks source link

Add perspective transformations #60

Closed samizdatco closed 2 years ago

samizdatco commented 2 years ago

Skia has support for 3D perspective transformations that the canvas standard lacks (despite the DOMMatrix class being able to represent them). This patch adds a new factory method to the Context object called createProjection to help create DOMMatrix objects that map from the default (rectangular) coordinate system to an arbitrary quadrilateral. With the appropriate trapezoidal shape for the quadrilateral, you can simulate vanishing-point perspective.

Addresses the use case from #48

To Do:

Example

let {width, height} = canvas,
    basis = [
      0, 0,
      width, height
    ],
    quad = [
      0, 0,
      width*.5, height*.25,
      width*.5, height*.75,
      0, height
    ];

let perspective = ctx.createProjection(quad, basis)
ctx.setTransform(perspective)

ctx.fillStyle = '#ddd'
ctx.fillRect(0, 0, width, height)

ctx.fillStyle = 'black'
ctx.textBaseline = 'middle'
ctx.font = '900 100px Avenir'
ctx.fillText("Twas brillig and the slithy toves did gyre and gimble in the wabe", 0, height*.5)

image