javascript - 任何人都可以告诉我如何使用 Canvas 将图像调整为特定大小和曲线

标签 javascript css html image canvas

我有一个用户将上传大图像的应用程序,我的应用程序中还有其他小图像。我想使用 Canvas 调整上传图像的大小和曲线。

我正在使用下面的代码。它正在 flex 图像,但我无法调整图像的大小。

var imageObj1 = new Image();
var imageObj2 = new Image();
imageObj1.src = "./images/mug_center.jpg"
imageObj2.src = dataImage;
var x1 = imageObj2.width / 2;
var x2 = imageObj2.width;
var y1 = 19; // curve depth
var y2 = 0;
var eb = (y2*x1*x1 - y1*x2*x2) / (x2*x1*x1 - x1*x2*x2);
var ea = (y1 - eb*x1) / (x1*x1);
// variable used for the loop
var currentYOffset;
for(var x = 0; x < imageObj2.width; x++) {
    // calculate the current offset
    currentYOffset = (ea * x * x) + eb * x;
    ctx.drawImage(imageObj2,x,0,1,imageObj2.height,x,currentYOffset,1,imageObj2.height);
}
var img = c.toDataURL("image/png");

最佳答案

这是一种方法:

  • 在临时 Canvas 上绘制曲线版本的图像。

  • context.scale 缩放主 Canvas

  • context.drawImage(tempCanvas...) 将 flex 的临时 Canvas 绘制到主 Canvas 上。

enter image description here

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;


var imageObj2=new Image();
imageObj2.onload=start;
imageObj2.src="https://dl.dropboxusercontent.com/u/139992952/multple/reef.jpg";
function start(){

  curvedScale(1.5)

}

function curvedScale(scale){
  var tempCanvas=document.createElement('canvas');
  var tctx=tempCanvas.getContext('2d');
  tempCanvas.width=imageObj2.width*scale;
  tempCanvas.height=imageObj2.height*scale*3;
  var x1 = imageObj2.width / 2;
  var x2 = imageObj2.width;
  var y1 = 19; // curve depth
  var y2 = 0;
  var eb = (y2*x1*x1 - y1*x2*x2) / (x2*x1*x1 - x1*x2*x2);
  var ea = (y1 - eb*x1) / (x1*x1);
  // variable used for the loop
  var currentYOffset;
  var maxY=0;
  for(var x = 0; x < imageObj2.width; x++) {
    // calculate the current offset
    currentYOffset = (ea * x * x) + eb * x;
    if(currentYOffset>maxY){maxY=currentYOffset;}
    tctx.drawImage(
      imageObj2,
      x,0,1,imageObj2.height,
      x,currentYOffset,1,imageObj2.height
    );
  }
  ctx.scale(scale,scale);
  ctx.drawImage(tempCanvas,0,0,tempCanvas.width,tempCanvas.height);
  ctx.scale(-scale,-scale);
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<h4>Canvas with 1.50X scale</h4>
<canvas id="canvas" width=600 height=400></canvas>
<h4>Original Image</h4>
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/reef.jpg'>

关于javascript - 任何人都可以告诉我如何使用 Canvas 将图像调整为特定大小和曲线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30390672/

相关文章:

javascript - Stripe 似乎创建了弹出窗口,但在移动设备上将其关闭

javascript - AJAX 请求有效负载未显示在控制台日志中

javascript - 如何在不将 overflow-x 更改为 auto 的情况下使 overflow-y 滚动?

javascript - ExpressionEngine cms 中的定位问题

javascript - 如何让元素而不是元素漂浮在主体内部

javascript - SVG 过渡不起作用

javascript - 从浏览器(Windows 或 MacOS)在 Zebra 打印机上打印数据

javascript - 根据图像选择更改背景图像 CSS 属性

html - 如何使用大括号作为Div的左右边界

php - 在 php 中使用 mPDF 将 html 转换为 pdf 时出现对齐干扰