javascript - Canvas 如何管理图像的比例

标签 javascript html canvas

全部:

我想知道如果我在canvas上绘制图像,如果图像比例不适合canvas,canvas如何缩放它(假设在canvas上只设置宽度和高度)?

例如:

<canvas id="myCanvas" style="width:200px; height:200px;"></canvas>
<script>
    var canvas = d3.select("#myCanvas").node();
    var context = canvas.getContext("2d");

    var img = new Image();

    img.onload = function(){
        console.log(img.naturalWidth, img.naturalHeight);
        context.drawImage(img, 0, 0);
    }

    img.src = "https://www.google.com/images/srpr/logo11w.png";
</script>

结果似乎图像已经垂直拉伸(stretch)了一点,水平挤压了一点,我想知道为什么canvas会这样处理它以及如何按原样绘制它或按比例缩放?

我也尝试在绘制图像时给出宽度和高度,但似乎仍然不太正确,例如:

// in this way, the image still get stretched and squeeze
<script>
    var canvas = d3.select("#myCanvas").node();
    var context = canvas.getContext("2d");

    var img = new Image();

    img.onload = function(){
        console.log(img.naturalWidth, img.naturalHeight);
        context.drawImage(img, 0, 0, img.naturalWidth/5, img.naturalHeight/5);
    }

    img.src = "https://www.google.com/images/srpr/logo11w.png";
</script>

或者

// Even I give it a 100 by 100 size, it can not do it that way
<script>
    var canvas = d3.select("#myCanvas").node();
    var context = canvas.getContext("2d");

    var img = new Image();

    img.onload = function(){
        console.log(img.naturalWidth, img.naturalHeight);
        context.drawImage(img, 0, 0, 100, 100);
    }

    img.src = "https://www.google.com/images/srpr/logo11w.png";
</script>

谢谢

最佳答案

Canvas 的位图默认为 300x150,与 CSS 大小无关。

<canvas id="myCanvas" style="width:200px; height:200px;"></canvas>

这将拉伸(stretch)绘制到 300x150 位图的任何内容以适合 200x200 CSS 尺寸。

使用 Canvas 的属性(或来自 JavaScript 的属性)来正确设置尺寸:

<canvas id="myCanvas" width=200 height=200></canvas>

关于javascript - Canvas 如何管理图像的比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30511877/

相关文章:

javascript - 将动态变量传递到jquery语句中

javascript - 我将 X Y Z 坐标转换为屏幕 X Y 坐标有什么问题?

javascript - 如何在HTML5 Canvas 上正确绘制多条不同宽度的线条?

google-maps - 谷歌地图 V3 : Disable Canvas Markers

delphi - 如何制作透明背景的tmemo和Tedit?

javascript - 在react js中解析JSON

javascript - 有没有办法通过javascript中的appium获取按钮的绝对位置

javascript - 在 jQuery 中创建一个对象数组

HTML/CSS : How to add Custom Banner in phpBB Style

android - 如何对颜色进行 alpha mask