I have a picture on canvas that I want to do a trapezoidal distortion on. The code itself is ready, but it is slow, very slow. 400x400 images in ~10-20 seconds on an i7 desktop machine. However, I want to run this on a mobile device with maximum camera resolution, so I'm looking for a more efficient way. Currently, my code works like this:
Is there a more efficient way to do this?
As your essentially operating on the pixel level things have to be pretty slow. The fastest way would be to utilize WebGL and outsource the calculations to a fragment shader. That might be a bit of an overkill in this case though. If all you want to do is perspectively transform an image, there's a ready-to-use tiny library - though not as acurate as on the pixel level - which might suite your needs called perspective.js
All you have to do is feed it an image and your desired four corner points.
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([
[65,43],
[266, 16],
[304,251],
[26,151]
]);
}
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" width="400" height="300"></canvas>