gpt4 book ai didi

javascript - 调整 Canvas 内的图像

转载 作者:行者123 更新时间:2023-11-30 15:09:01 26 4
gpt4 key购买 nike

生成图像时在 Canvas 内调整图像大小。

我正在尝试生成图像。我将图像从图像转换为数据图像,然后将其编码为图像。然后将其放入 Canvas 元素中。宽度的大小为 300px,高度的大小为 311px。但是图像没有重新缩放。我该如何解决这个问题?

https://jsfiddle.net/svvmrwvv/

<canvas id="result" width="300" height="310"></canvas>
<br>
<div class='frames'></div>

var res_c = document.getElementById("result");
var res_ctx = res_c.getContext('2d');
var width = 300;
var height = 311;

//codifing image

var image = new Image;
image.src = 'http://tosemdinheiro.com/wp-content/uploads/2012/10/carro.jpg';
res_ctx.drawImage(image, 0, 0);
imageData = res_ctx.getImageData(0, 0, width, height);
console.log(imageData);

//decodifing image

var image_gif = new Image();
image_gif.src = res_c.toDataURL("image/png");
image_gif.height=width;
console.log(image_gif)
image_gif.width=height;
$(".frames").append(image_gif);

enter image description here

最佳答案

您需要等待图片加载完成后才能进行修改。当您渲染它时,您必须以您想要的尺寸渲染它。 drawImage函数有多个版本,其中之一是 ctx.drawImage(image,x,y,width,height)它将在 x 处绘制图像, y尺寸为 width , height .

const canvas = document.getElementById("result");
const ctx = canvas.getContext('2d');
const width = 300;
const height = 311;
const image = new Image;
image.src = 'http://tosemdinheiro.com/wp-content/uploads/2012/10/carro.jpg';
image.onload = function(){ // wait for the image to load
ctx.canvas.width = width; // set size
ctx.canvas.height = height;
ctx.drawImage(image,0,0,width,height); // draw the image at size

// Dont know why you are doing the following so removed it
//const imageData = res_ctx.getImageData(0, 0, width, height);

// create new image
const imageGif = new Image;
imageGif.src = canvas.toDataURL(); // "image/png" is the default mime type
document.querySelector(".frames").appendChild(imageGif);
}

关于javascript - 调整 Canvas 内的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45378163/

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