画布上的图像绘制比原始尺寸大

Image on Canvas is drawn larger than original size

本文关键字:原始 绘制 图像      更新时间:2023-09-26

On load my image I:

var img = new Image();
img.src = e.target.result;
var canvas = $('#test-canvas')[0];
$('#test-canvas').width(img.width);
$('#test-canvas').height(img.height);
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);

但是绘制的图像比原始尺寸大?我已经尝试了一些图像,同样的问题。

解决办法是什么?

jQuery将通过CSS调整元素的大小,这实际上不会改变画布内部的高度和宽度。这将调整实际画布元素的大小。

var canvas = document.GetElementById('test-canvas');
canvas.width  = img.width;
canvas.height = img.height;

jsFiddle (http://jsfiddle.net/L0drfwgL/)只是显示它绘制它的比例,并调整画布项目本身的大小。

看起来您正在从加载的image元素中提取图像。您可以使用来自image元素的src,而不是重新创建一个图像对象,然后从元素获取图像的宽度/高度,将图像绘制到画布上。

<script>
    $(document).ready(function(){
        $('#testImg').on('load',function(){
            var image = document.getElementById('testImg');
            var canvas = document.getElementById('test-canvas');
            canvas.width = image.width;
            canvas.height = image.height;
            var ctx=canvas.getContext("2d");
            ctx.drawImage(image,0,0);
        })
    });
    </script>

/** with vue3 -(to fix drawing canvas image is larger than actual image size **/
const captureImage = () => {
  let width = video.value.getBoundingClientRect().width;
  let height = video.value.getBoundingClientRect().height;
  let context = canvas.value.getContext('2d')
  canvas.value.width = width
  canvas.value.height = height
  context.drawImage(video.value, 0, 0, width, height)
}