繁体   English   中英

HTML5 Canvas - 来自HTML大小调整图像的drawImage

[英]HTML5 Canvas - drawImage from a HTML resized image

为什么在HTML中的img标签中设置widthheight属性时,不会调整简单的drawImage()调用?

这是一个jsfiddle演示来展示我的意思。

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);
}   

在该演示中,如果在唯一的img标签上设置width属性,您将看到左侧的图像更改(原始图像),但右侧的图像不会(drawImage渲染)。

我知道我将testImage.src设置为原始src,但我也设置了宽度和高度,如果打开开发人员控制台日志,则会调整宽度和高度。

为什么是这样? 我可以调整该代码,以便相应调整吗?

这里的预期结果是drawImage渲染显示图片的更大区域。 很容易判断它没有调整大小 - “无限”符号是不同的大小,它们应该是相同的。

您无法更改原始图像的大小。 您只能使用CSS重新调整大小,这会导致缩放 - 但原始大小将是原始大小,因此更改图像的宽度和高度属性将不起作用(为了缩放它,您可以使用img.style.width和img.style.height,但这不会影响数据本身,只会将其呈现给浏览器窗口)。

对于画布和绘制较小的较大图像,您必须在目标上设置新的大小而不是

修改小提琴:
http://jsfiddle.net/L3495/4/

(在你的图像onload事件中):

context.drawImage(this, 0, 0, this.width, this.height,
                        0, 0, newWidth, newHeight);

在这里,您使用与原始图像相同的绘制。 这里的来源告诉画布使用整个图像。

然后用你想要的尺寸把它画到目的地

在小提琴中你看到我为原始图像设置了画布的半尺寸以进行演示。 这将是为目标值绘制图像的大小。

将对象放在DOM中时,图像对象的widthheight属性仅由浏览器的呈现引擎使用。

drawImage调用中,您可以指定目标位置(不进行缩放),目标矩形(将完成缩放)或目标和源矩形(缩放将完成)。

使用drawImage时,图像的.width.height属性无关紧要。

加载图像后,您可以使用.width.height来检测原始大小,但更改它们只会影响在DOM中完成该对象的渲染。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM