javascript - 将图像加载到 Canvas 中 - 图像缩放

标签 javascript css canvas drawimage

我在将图像加载到 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/

相关文章:

javascript - 移动 chrome 和模式的奇怪行为

JavaScript 在 jQuery 和 AJAX 中自动递增变量

javascript - 页面加载后,按钮仅在第二次单击时有效

javascript - 如何在 HTML5 canvas 中为球变小制作动画

javascript - 如何从javascript函数中获取值?

php - 对用户上传的图像使用 Photoshop Actions

javascript - 使用 VueX Store 中的计算属性进行 Ajax 调用的正确方法是什么

javascript - 屏幕记录网页上的视差元素?

html - Flex-box 并排显示子 div

canvas - D3 Canvas 地球仪鼠标事件