【发布时间】:2015-05-28 16:10:42
【问题描述】:
全部:
我想知道如果我在画布上绘制图像,如果图像比例不适合画布,画布如何缩放它(假设画布上只设置宽度和高度)?
例如:
<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>
结果似乎图像被垂直拉伸了一点,水平挤压了,我想知道为什么画布会这样处理它,以及如何按原样绘制或按比例缩放?
我也试过在画图的时候给出宽度和高度,但还是不太对,例如:
// 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>
谢谢
【问题讨论】:
标签: javascript html canvas