2017-07-28 49 views
1

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

我正在尝试生成图像。从图像转换成dataImage,后来我将它编码成图像。然后把它放在一个画布元素里面。宽度的大小为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

+0

你为什么不设置'width'和'height'在渲染''元素 – guest271314

+0

@ guest271314但图像没有完全显示 – yavg

+0

@ guest271314对不起,也许我不理解你。 – yavg

回答

2

你需要等待图像加载之前,你可以修改它。当你渲染它时,你必须按照你想要的尺寸渲染它。 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); 
}