【发布时间】:2011-05-09 04:11:37
【问题描述】:
我正在尝试将图像放置在画布上而不调整其大小。我认为 drawImage(img, x, y) 可以解决问题,但它会拉伸图像以填充画布。 还提供带有我图像尺寸的 drawImage(img, x, y, width, height) 似乎不起作用。
这是我的代码:
<canvas id="story" style="position:relative; width:800px; height:600px;"></canvas>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById("story");
var context = canvas.getContext("2d");
var img = document.getElementById("img1");
var width = parseInt(img.width);
var height = parseInt(img.height);
context.drawImage(img, 0, 0, width, height);
}
</script>
<img id="img1" alt="" src="http://link to image"/>
提前致谢!
PS:我添加了 parseInt 以确保 drawImage 获得有效值。
【问题讨论】:
-
当我调用
drawImage(在 Firefox 3.6 和 Chrome 9 中)时,它不会拉伸以填充画布。您能否向我们展示一个发生这种情况的示例 (jsfiddle)?
标签: javascript image html canvas