全部:
我想知道如果我在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/