我尝试在画布上放置一个图像,而不调整它的大小。我以为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获得有效的值。
发布于 2010-11-13 00:36:30
不要使用CSS来调整画布的大小。这会创建一个默认大小的画布并拉伸它。直接在上面设置画布尺寸,你会得到1到1个像素的绘图空间。
<canvas id="story" width="800" height="600" style="position:relative;"></canvas>
发布于 2010-11-13 01:30:31
Trochoid是对的,画布标签上的style属性导致了问题。您可以按照他的建议在HTML中设置它,或者更好的做法是将它留空并在JS中动态设置:
<canvas id="story"></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);
canvas.height=height;
canvas.width=width;
context.drawImage(img, 0, 0);
}
</script>
<img id="img1" alt="" src="http://link to image"/>
发布于 2010-11-13 02:39:26
还要确保获得图像的宽度和高度,并在加载后绘制它。
img.onload = function () {
var width = parseInt(img.width);
var height = parseInt(img.height);
context.drawImage(img, 0, 0, width, height);
};
https://stackoverflow.com/questions/4166645
复制相似问题