【问题标题】:Canvas draw new image from daturl画布从 daturl 绘制新图像
【发布时间】:2014-05-03 03:40:34
【问题描述】:

我正在使用下面的函数来使用画布调整大小和图像

var img = new Image();
img.src = reader.result;
img.onload = function() {

    var max_width = 800;
    var max_height = 800;
    var tempW = img.width;
    var tempH = img.height;
     var aspect_ratio = 1;
    if (tempW > tempH) {
        if (tempH > max_height){
          var aspect_ratio = tempH / max_height
                       }
    } else {

            if (tempW > max_width){
          var aspect_ratio = tempW / max_width
                       }


    }
    tempH = tempH / aspect_ratio;
    tempW = tempW / aspect_ratio;

    var canvas = document.createElement('canvas')
     canvas.id = "uploadedcanvas";
    canvas.width = tempW;
    canvas.height = tempH;
    var ctx = canvas.getContext("2d");
ctx.fillStyle="#FFFFFF";
    ctx.fillRect(0,0,tempW,tempH); 
    ctx.drawImage(this, 0, 0, tempW, tempH);
    var dataURL = canvas.toDataURL("image/jpeg");

   createsecondimage(dataURL,tempW,tempH,max_width,max_height,canvas)


   }

这可以调整从文件阅读器获取的图像的大小。我想使用 dataURL 作为图像源在同一个画布中创建第二个图像,但这似乎不起作用这就是我正在做的事情

    function createsecondimage(dataURL,tempW,tempH,max_width,max_height,canvas){
var copy = document.createElement('canvas');
    copy.width = max_width;
    copy.height = max_height;
    var copyctx = copy.getContext("2d");
var sx = (tempW - max_width) / 2
    var sy = (tempH - max_height) /2
   copyctx.fillStyle="#FFFFFF";
    copyctx.fillRect(0,0,max_width,max_height); 
   var imgcopy = new Image();
        imgcopy.src = dataURL;
        imgcopy.onload = function() {
      copyctx.drawImage(imgcopy, sx, sy, 800, 800,0, 0, 800, 800);
var dataURL_ = copy.toDataURL("image/jpeg");

        }

但是 datURL_ 似乎是空的。我不确定为什么会这样。理想情况下,我想使用刚刚调整大小的图像创建一个新图像。

【问题讨论】:

  • 尝试设置 imgcpy.src after onload。另外,请使用copyctx.drawImage(this, ...) 而不是 imgcopy。
  • 我认为你应该等待这一行 var dataURL = canvas.toDataURL("image/jpeg");直到画布被绘制
  • @Epistemex 感谢工作!
  • @user3593876 非常好。我会把它变成一个答案,这样问题就可以结束了。

标签: javascript html image canvas


【解决方案1】:

您可以进行以下两项更改,它应该可以工作:

  • 设置imgcpy.src加载之后。
  • 使用copyctx.drawImage(this, ...) 而不是imgcopy

这样您可以确保在调用 onload 之前未完成图像的解码和设置,并且this 将拥有对正在解码的图像的有效引用。

【讨论】:

  • 这可行,但是 dataURL_ 为空。你知道为什么会这样吗?
  • @rolinstoner 很可能是范围问题(基于示例代码)。您可以将其传递给您在将其设置为图像加载是异步的之后调用的函数。还要检查控制台是否存在安全错误(由于 CORS)。如果图像是从外部站点加载的,就会发生这种情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多