【问题标题】:Should I specify height and width to canvas new Image() constructor?我应该为画布 new Image() 构造函数指定高度和宽度吗?
【发布时间】:2015-02-12 09:44:18
【问题描述】:

我在所有画布图像创建文档 (https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images) 中都看到了新的图像构造函数,例如myImg = new Image();,就像没有参数一样使用。但是,我知道它需要宽度和高度的可选参数,例如myImg = new Image(400,300);

如果您事先知道图像的宽度和高度,那么指定这些参数是否是一种好习惯?

在构造函数之后我使用myImg.src = 'myurl.jpg';myImg.onload = function() { ctx.drawImage(myImg, x, y)...};

【问题讨论】:

    标签: html image canvas html5-canvas


    【解决方案1】:

    如果您要将新图像绘制到画布上,则无需在图像的构造函数中指定图像大小。图片在myImg.onload 中完全加载后,Javascript 会知道图片的原生大小。

    当您使用context.drawImage 在画布上绘制图像时,默认情况下图像将以其原始大小绘制。但是您也可以使用 drawImage 的额外参数指定不同的图像大小:

    // draw myImg on the canvas in the top-left corner
    // and resize the image to half-size
    context.drawImage(myImg, 0,0, myImg.width/2, myImg.height/2);
    

    如果您希望画布与图像大小相同,则必须调整 myImg.onload 内的画布大小,这是 javascript 第一次知道图像的原生大小:

    // create the canvas element its context
    var canvas=document.createElement('canvas');
    var context=canvas.getContext('2d');
    
    // create the image object
    var img=new Image();
    img.onload=start;
    img.src="myImage.png";
    function start(){
    
        // The native image size is now known,
        // so resize the canvas to the same size as the image
        canvas.width=img.width;
        canvas.height=img.height;
    
        // draw the image on the canvas
        context.drawImage(img,0,0);
    }
    

    【讨论】:

    • 太棒了!感谢您澄清为什么应该这样做并添加其他要点。
    猜你喜欢
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多