当在 HTML 的标签中设置了width
orheight
属性时,为什么一个简单的 drawImage() 调用不会调整?img
HTML
<!--Try adding width="200" to the img tag below.
You'll see that the original image (left on
the output) is resized accordingly, but the
drawImage rendering is not. If you console.log
imgs.width, it's set to 200, but the
result is unchanged.
-->
<img src="https://i.imgur.com/mbXJe0f.png" width="200">
JavaScript
imgs = document.getElementsByTagName('img')[0];
//I set EVERYTHING I know about to the proper values, just to see what happens
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
style = '';
style += 'width:'+imgs.width+'px;';
style += 'height:'+imgs.height+'px;';
canvas.setAttribute('style',style);
canvas.width = imgs.width;
canvas.height = imgs.height;
console.log(imgs.width,imgs.height);
var testImage = new Image();
testImage.src = imgs.src;
testImage.width = imgs.width;
testImage.height = imgs.height;
testImage.onload = function() {
square = 100;
context.drawImage(this,150,70,square,square,0,0,square,square);
}
在那个演示中,如果你width
在唯一img
标签上设置属性,你会看到左边的图像发生了变化(原始的),但右边的图像没有变化(drawImage 渲染)。
我知道我正在设置testImage.src
为原始 src,但我也在设置宽度和高度,如果你打开开发者控制台日志,它们会被调整。
为什么是这样?我可以调整该代码以使其相应调整吗?
这里的预期结果是 drawImage 渲染显示图片的更大区域。很容易看出它没有调整大小 - “无穷大”符号的大小不同,它们应该是相同的。