我在将图像加载到 Canvas 时遇到问题 - 图像以某种方式缩放。
背景:我的网页上有几个 Canvas ,我想将图像加载到它们中。构建时,我不确定尺寸,因为尺寸取决于屏幕尺寸。
因此,我创建了 div 和 Canvas ,使用 css 将其设置为我想要的大小,并将图像打印到 Canvas 上。图像会有更多的事情要做(即,如果我需要将它垂直或水平居中,则根据比例来决定),但这些在这一点上并不重要。问题是图像被“缩放”了。
示例:javascript 片段在这里:
$("canvas").each(function() {
var context = $(this)[0].getContext('2d');
var img = new Image;
img.src = 'http://i67.tinypic.com/n38zdv.jpg';
$(img).load(function() {
context.drawImage(this, 0, 0);
});
//img will print 400 (correct, thats the width of the img)
//canvas will print based on the screen size (correct)
//img displayed in the canvas shows 300px out of 400px, it's zoomed (not correct)
$(this).parent().append(
'img width: '+img.width+
', canvas width: '+$(this).width());
});
我把整个例子和 HTML 和 CSS 放到了 https://jsfiddle.net/7zdrfe58/11/ .
我正在尝试使用 Mac。 Safari 和 Chrome 的工作原理相同(即缩放)。
非常感谢对此的帮助!!非常感谢
最佳答案
drawImage
允许您指定图像的宽度和高度。您可以像这样获得 Canvas 宽度:
$("canvas").each(function() {
var canvas = this;
var context = canvas.getContext('2d');
var img = new Image;
img.src = 'http://i67.tinypic.com/n38zdv.jpg';
$(img).load(function() {
context.drawImage(this, 0, 0, canvas.width, canvas.height);
});
});
在此处检查您的工作代码:
https://jsfiddle.net/ucxdLsq9/
drawImage
签名的文档可以在这里找到:
https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/drawImage
关于javascript - 将图像加载到 Canvas 中 - 图像缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36449251/