Question

I am trying to draw crop an image and draw it onto the canvas but when ran in the browser the canvas remains white. no errors appear.

var imgSprite = new Image();
imgSprite.src = 'sprite.png';
imgSprite.addEventListener('load', init, false);

function init(){
    drawBg();

}
function drawBg() {
    var sourceX =0;
    var sourceY =0;
    var sourceWidth =800;
    var sourceHeight =500;
    var destWidth =800;
    var destHeight =500;
    var destX =0;
    var destY =0;
    //ctxBg.clearRect(0, 0, gameWidth, gameHeight);
    ctxBg.drawImage(imgSprite, sourceX,sourceY,sourceWidth,sourceHeight,
        destWidth,destHeight,destX,destY);
}
Was it helpful?

Solution

The last four parameters to drawImage are in the wrong order. It should be:

ctxBg.drawImage(imgSprite, sourceX,sourceY,sourceWidth,sourceHeight,
        destX,destY,destWidth,destHeight); // x,y before width,height

See CanvasRenderingContext2D drawImage() for all the overloads and interactive examples.

OTHER TIPS

Your parameter set is not matching any of the available parameter sets for drawImage()

ctxBg.drawImage(imgSprite, 0, 0, gameWidth, gameHeight);

Demo: Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top