如何避免HTML Canvas自动拉伸 [英] How to avoid HTML Canvas auto-stretching

查看:124
本文介绍了如何避免HTML Canvas自动拉伸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆