2016-12-15 54 views
0

我試圖從單擊提交按鈕後,從圖像大小調整爲像素,但我可以實現的所有裁剪原始圖像。它看起來像改變後的大小畫布不刷新圖像。我如何正確地做到這一點?上jsfiddle畫布調整大小與其中的圖像

JS代碼

實施例:

document.addEventListener("DOMContentLoaded", function() { 
    var width = 0; 
    var height = 0; 
    var colors = 0; 
    var order = 0; 

var canvas = document.getElementById('project'); 
var context = canvas.getContext('2d'); 
var logo = document.getElementById('logo'); 

logo.onload = function() { 
    canvas.width = logo.width; 
    canvas.height = logo.height; 

    context.drawImage(logo, 0, 0); 
}; 

document.getElementById("btn_sub").addEventListener("click", function(event) { 
    event.preventDefault(); 

    width = document.getElementById("form1").elements[0].value; 
    height = document.getElementById("form1").elements[1].value; 
    colors = document.getElementById("form1").elements[2].value; 
    order = document.getElementById("form1").elements[3].value; 

    logo.width = (width * 118)/25.4; 
    logo.height = (height * 118)/25.4; 

    canvas.width = (width * 118)/25.4; 
    canvas.height = (height * 118)/25.4; 

    context.clearRect(0, 0, canvas.width, canvas.height); 
    context.drawImage(logo, 0, 0); 

回答

0

的的drawImage函數未考慮到圖像元素的寬度和高度。爲了使這個工作,你可以使用這個重載的drawImage函數context.drawImage(img,x,y,width,height)

像這樣的例子,context.drawImage(logo, 0, 0, logo.width, logo.height)