Canvas Curve
by Hooman Askari
HTML
<img src="https://i.imgur.com/BuNasz4.jpg" id="image" />
JavaScript
// var canvas = document.getElementById('canvas');
// var ctx = canvas.getContext('2d');
var img = document.getElementById('image');
// var x1 = img.width / 2;
// var y1 = 55; // curve depth
// var x2 = img.width;
// var y2 = 0;
// var eb = (y2*x1*x1 - y1*x2*x2) / (x2*x1*x1 - x1*x2*x2);
// var ea = (y1 - eb*x1) / (x1*x1);
const calcYOffset = (a, b, x, curve) => {
// calculate the current offset
var currentYOffset = (a * x * x) + b * x;
// If the curve goes upwards
if (curve < 0) currentYOffset = currentYOffset - curve;
return currentYOffset;
}
const curveImage = (img, curve, start, canvas) => {
var canvas = canvas || document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height + Math.abs(curve);
const ctx = canvas.getContext('2d');
const x1 = 300;
const y1 = curve;
const x2 = img.width;
const y2 = 0;
const b = (y2*Math.pow(x1,2) - y1*Math.pow(x2, 2)) / (x2*Math.pow(x1,2) - x1*Math.pow(x2, 2));
const a = (y1 - b*x1) / Math.pow(x1,2);
for(let x = 0; x < img.width; x++) {
// console.log(calcYOffset(a, b, x, curve))
ctx.drawImage(img,
x, // sx
0, // sy
1, // sWidth
img.height, // sHeight
x, // dx
calcYOffset(a, b, x, curve), // dy
1, // dWidth
img.height // dHeight
);
}
return canvas;
}
var newImage = document.createElement('img');
newImage.setAttribute('crossOrigin', 'Anonymous');
newImage.src = 'https://i.imgur.com/BuNasz4.jpg';
newImage.onload = function() {
img.src = curveImage(this, 15).toDataURL();
}
//var y1_2 = -55; // curve depth
//var eb_2 = (y2*x1*x1 - y1_2*x2*x2) / (x2*x1*x1 - x1*x2*x2);
//var ea_2 = (y1_2 - eb_2*x1) / (x1*x1);
// variable used for the loop
//var currentYOffset;
//for(let x = 0; x < img.width; x++) {
// calculate the current offset
// currentYOffset = (ea * x * x) + eb * x;
// ctx.drawImage(img,
//x, // sx
//0, // sy
//1, // sWidth
//img.height, // sHeight
//x, // dx
//currentYOffset, // dy
//1, // dWidth
//img.height...