简体   繁体   English

帆布从曼陀罗绘制新图像

[英]Canvas draw new image from daturl

I'm using the function below to resize and image using canvas 我正在使用下面的功能来调整大小和使用画布图像

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)


   }

This is able to resize an image from taken from file reader. 这能够调整从文件阅读器获取的图像大小。 I would like to create a second image in the same canvas using the dataURL as the image source but this it does not seem to work this is what I'm doing 我想在同一画布中使用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");

        }

However datURL_ appears to be empty. 但是datURL_似乎为空。 I'm not sure why this is the case. 我不确定为什么会这样。 Ideally I would want to create a new image using the image that was just resized. 理想情况下,我想使用刚刚调整大小的图像来创建新图像。

You can do the following two changes and it should work: 您可以进行以下两个更改,它应该可以工作:

  • set imgcpy.src after onload. onload 之后设置imgcpy.src
  • Use copyctx.drawImage(this, ...) instead of imgcopy . 使用copyctx.drawImage(this, ...)代替imgcopy

This way you are making sure decoding and setting of image is not completed before onload is called, and this will have a valid reference to the image being decoded. 这样,您可以确保在调用onload之前未完成图像的解码和设置, this将对正在解码的图像具有有效的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM