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);
}
有帮助吗?

解决方案

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.

其他提示

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

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

Demo: Fiddle

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top