javascriptjquerycanvas

Create Canvas element with image and append to parent


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

<html>
<head>
    <script>
        window.onload = function() {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext("2d");
        canvas.id = "canvas_id";
        canvas.setAttribute("class" ,"canvas");
        canvas.height =  "400";
        canvas.width =  "800";
        var image = new Image();
        image.src = "http://localhost/tile.png";
        image.onload = function(){
           context.drawImage(image, canvas.width, canvas.height);
        }
        document.body.appendChild(canvas);
    }
</script>
</head>
<body>
</body>
</html>

it give blank canvas

can somebody guide me ?


Solution

  • You are using drawImage() the wrong way. Instead of drawing the image at (0,0) you are drawing it just outside the canvas area as width and height is where position normally goes.

    The valid signatures are:

    context.drawImage(image, dx, dy)
    context.drawImage(image, dx, dy, dw, dh)
    context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)

    Where dx and dy are delta position (relative to origin, normally (0,0) when untranslated). Without width and height specified drawImage() will by default use the image's natural width and height.

    The second version allows to override the default size, and the third will allow you to draw from one region to another.

    Source

    Corrected example:

    window.onload = function() {
      var canvas = document.createElement('canvas');
      var context = canvas.getContext("2d");
      canvas.id = "canvas_id";
      canvas.className = "canvas";                  // should be className
      canvas.height = 400;                          // should be numbers
      canvas.width = 800;
      var image = new Image();
      image.onload = function() {
        // or set canvas size = image, here: (this = currently loaded image)
        // canvas.width = this.width;
        // canvas.height = this.height;
        context.drawImage(this, 0, 0);              // draw at (0,0), size = image size
    
        // or, if you want to fill the canvas independent on image size:
        // context.drawImage(this, 0, 0, canvas.width, canvas.height);
      }
      // set src last (recommend to use relative paths where possible)
      image.src = "http://lorempixel.com/output/fashion-q-c-800-400-7.jpg";
      document.body.appendChild(canvas);
    }

    That being said, if you only need the image appended there is no need to go via canvas. Just add the image to DOM directly (I assume this is not you want, but just in case..):

    var image = new Image();
    image.src = "tile.png";
    document.body.appendChild(image);