gpt4 book ai didi

javascript - canvas.drawImage 使裁剪后的图像不成比例

转载 作者:行者123 更新时间:2023-11-30 16:48:34 29 4
gpt4 key购买 nike

渲染以下图像时(右键单击 + 查看图像以查看完整尺寸):

http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png

大小为 4800x320 的 html5 canvas.drawImage() 并尝试从中裁剪部分 480x320 图像, Canvas 将图像放大。

这是我的代码:

var canvas = document.createElement('canvas');
canvas.setAttribute('id', 'my-canvas');
canvas.style.width = 480;
canvas.style.height = 320;
canvas.style.display = 'block';

document.body.appendChild(canvas);

var img=document.createElement('img');
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png';
img.onload = function () {
var c=document.getElementById('my-canvas');
var ctx=c.getContext('2d');
ctx.drawImage(img,480,0,480,320,0,0,480,320);
}

另外,当我将图像绘制成较小比例时,它突然适合:

var canvas = document.createElement('canvas');
canvas.setAttribute('id', 'my-canvas');
canvas.style.width = 480;
canvas.style.height = 320;
canvas.style.display = 'block';

document.body.appendChild(canvas);

var img=document.createElement('img');
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png';
img.onload = function () {
var c=document.getElementById('my-canvas');
var ctx=c.getContext('2d');
ctx.drawImage(img,480,0,480,320,0,0,240,160);
}

谁知道这是为什么?

最佳答案

Canvas 的默认位图 大小为 300x150 像素。设置 CSS 大小不会改变位图大小。位图直接在元素上设置了自己的宽度/高度属性/属性。否则,位图将被拉伸(stretch)以填充元素 CSS 大小。

改变这些:

canvas.style.width = 480;
canvas.style.height = 320;

canvas.width = 480;
canvas.height = 320;

您还可以设置代码以重用上下文:

//var c=document.getElementById('my-canvas'); // you already have this as canvas
var ctx=canvas.getContext('2d'); // global/parent scope

var img=document.createElement('img');
img.src='http://cdn.cocimg.com/bbs/attachment/Fid_14/14_29173_56b5563d9a81a86.png';
img.onload = function () {
ctx.drawImage(img,480,0,480,320,0,0,480,320);
}

关于javascript - canvas.drawImage 使裁剪后的图像不成比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30884082/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com