如何避免HTML Canvas自动拉伸 [英] How to avoid HTML Canvas auto-stretching
问题描述
我有以下HTML:
< style type =text / css>
#c {width:200px; height:500px}
< / style>
< canvas id =c>< / canvas>
< script type =text / javascript>
var i = new Image();
i.onload = function(){
var ctx = document.getElementById('c')。getContext('2d');
ctx.drawImage(i,0,0);
}
i.width = i.height = 20; // actual size of square.png
i.src ='square.png';
< / script>问题是绘制图像会根据画布的大小按比例自动拉伸(调整大小)。
<我尝试使用所有可用的参数( drawImage(i,0,0,20,20,0,0,20,20)
/ p>
是什么原因导致我的绘图拉伸,如何防止这种情况?
谢谢,
Tom
您需要 width
和 height
属性。它们指定画布的坐标空间。显然,它默认是一个2:1宽高比的画布,你的CSS倾斜成一个正方形。
I have the following piece of HTML:
<style type="text/css">
#c{width:200px;height:500px}
</style>
<canvas id="c"></canvas>
<script type="text/javascript">
var i = new Image();
i.onload = function () {
var ctx = document.getElementById('c').getContext('2d');
ctx.drawImage(i, 0, 0);
}
i.width = i.height = 20; // actual size of square.png
i.src = 'square.png';
</script>
The issue is that the drawn image is automatically stretched (resized) proportionally with the size of the canvas. I have tried using all available parameters (drawImage(i, 0, 0, 20, 20, 0, 0, 20, 20)
) and that didn't help.
What is causing my drawing to stretch and how can I prevent that?
Thanks,
Tom
You need the width
and height
attributes in the canvas element. They specify the coordinate space for the canvas. Apparently, it defaults to a canvas of a 2:1 aspect ratio, which your CSS is skewing into a square.
这篇关于如何避免HTML Canvas自动拉伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!