我正在尝试将图像放置在 Canvas 上而不调整其大小。我认为 drawImage(img, x, y) 可以解决问题,但它会拉伸(stretch)图像以填充 Canvas 。 另外,为 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 获得有效值。
最佳答案
不要使用 CSS 来调整 Canvas 的大小。这会创建一个默认大小的 Canvas 并拉伸(stretch)它。直接在其上设置 Canvas 尺寸,您将获得 1 到 1 像素的绘图空间。
<canvas id="story" width="800" height="600" style="position:relative;"></canvas>
关于javascript - HTML5 Canvas : image resizing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4166645/