Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
148 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...