Create Canvas element with image and append to parent

前端 未结 2 1542
再見小時候
再見小時候 2020-12-11 10:55

I need to create Canvas element with image and need to append to parent for this i have done this



    

        
2条回答
  •  伪装坚强ぢ
    2020-12-11 11:16

    This is my take on it... You need to indicate the coordinates where you want to start drawing (i.e. 0, 0) and - optionally - you can specify how big (wide, height) the canvas is to be.

    In my case, I make the canvas to be as big as the image (instead of an arbitrary 400x800) you may need to update that your suit your requirements.

    I added some css to show how big the canvas is in relation to the image. You can update/remove that as well depending on your needs.

    UPDATED

    It uses an hidden image as the source.

    I hope this will work for you.

    window.onload = function() {
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext("2d");
      canvas.id = 'canvas_id';
      canvas.setAttribute("class", "canvas");
    
      var image = new Image();
      image.src = 'http://placekitten.com/g/200/300';
    
      canvas.width = image.width;
      canvas.height = image.height;
    
      ctx.drawImage(image, 0, 0, image.width, image.height);
      document.body.appendChild(canvas);
    }
    .canvas {
      border: solid red 1px;
    }
    
    
    
    
    
    
    

提交回复
热议问题