2017-07-28 80 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); 
}