Sora
Sora

Reputation: 2551

draw a part of an image inside a canvas

I have a canvas with width=400 and height=400 and an image with width =3392 and height=232. what I want to do cropping the first 400 px of this image and draw them inside the canvas how can I do this ?

$(document).ready(function () {
    var ctx = $("#MyCanvas")[0].getContext("2d"); // the "context" of the canvas that will be used (2D or 3D)
    var cw = 400; // width of the rectangular area
    var ch = 400; // height of the rectangular area
    var FieldImg= new Image(); // Image to be loaded and drawn on canvas
    var ImgNumb = 12; // Number of images that make up the movement
    var Fps = 30;
    init();
    function init() {
        FieldImg.src = "images/Spritebackground.png";
         ctx.drawImage(FieldImg, 0, 0, 400, 400, 0, 0, 400, 400); 
    }
});

ctx.drawImage(FieldImg, 0, 0, 400, 400, 0, 0, 400, 400);this line is not working ? this is my jsfiddle : http://jsfiddle.net/seekpunk/3uhgN/

Upvotes: 0

Views: 1946

Answers (1)

Philipp
Philipp

Reputation: 69663

You are setting the .src-attribute of the image and immediately try to draw it. This doesn't work because at that stage the image hasn't loaded yet. When you set a src-attribute, the image is loaded in the background while the rest of the code keeps executing. Until the image is loaded, it is treated as blank. So when you try to draw it, you are drawing a blank image. To solve this problem, move the drawing code into the onload-handler of the image.

Also, your source image is only 232px high, but your source rectangle is 400px high. You can't define a source-rectangle which is partly outside of the source.

 FieldImg.onload = function() {
      ctx.drawImage(FieldImg,0, 0, 400, 232,0, 0, 400, 400);
 }
 FieldImg.src = "images/Spritebackground.png";

Here is the updated JSFiddle: http://jsfiddle.net/jA93t/1/

Upvotes: 1

Related Questions