Canvas 上的图像绘制得比原始尺寸大
Image on Canvas is drawn larger than original size
加载我的图像时:
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 调整元素大小,这实际上不会改变 canvas 内部高度和宽度。这将调整实际 canvas 元素的大小。
var canvas = document.GetElementById('test-canvas');
canvas.width = img.width;
canvas.height = img.height;
jsFiddle (http://jsfiddle.net/L0drfwgL/) 只是展示它按比例绘制,并调整 canvas 项目本身的大小。
看起来您正在从加载的图像元素中拉取图像。您可以使用图像元素中的 src 而不是重新创建图像对象,然后从元素中获取图像 width/height 以将图像绘制到 canvas。
<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)
}
加载我的图像时:
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 调整元素大小,这实际上不会改变 canvas 内部高度和宽度。这将调整实际 canvas 元素的大小。
var canvas = document.GetElementById('test-canvas');
canvas.width = img.width;
canvas.height = img.height;
jsFiddle (http://jsfiddle.net/L0drfwgL/) 只是展示它按比例绘制,并调整 canvas 项目本身的大小。
看起来您正在从加载的图像元素中拉取图像。您可以使用图像元素中的 src 而不是重新创建图像对象,然后从元素中获取图像 width/height 以将图像绘制到 canvas。
<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)
}