Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

javascript - 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 ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...