Mar*_*kus 17 javascript html5 canvas image
我试图在没有调整大小的情况下将图像放在画布上.我想的drawImage(IMG,X,Y)会做的伎俩,但它拉伸图像填充画布.也与我的图像的尺寸的drawImage供给(IMG,X,Y,宽度,高度)似乎不工作.
这是我的代码:
<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"/>
Run Code Online (Sandbox Code Playgroud)
提前致谢!
PS:我添加了parseInt以确保drawImage获得有效值.
小智 21
不要使用CSS来调整画布大小.这会创建一个默认大小的画布并将其拉伸.直接在其上设置画布尺寸,您将获得1到1像素的绘图空间.
<canvas id="story" width="800" height="600" style="position:relative;"></canvas>
Run Code Online (Sandbox Code Playgroud)
Jef*_*eff 13
Trochoid是正确的,canvas标签上的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"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22875 次 |
| 最近记录: |