2017-06-07 124 views
-1

我想畫一個畫布,我在畫布中根據變量動態地改變形狀。我擁有的是如果想要改變怪物的形狀或者使它更大,我必須改變很多價值才能實現目標,我如何使我的所有號碼都變成現實,以便我在1個地方進行更改時,變化無處不在。Javascript畫布動態地改變形狀

Here is the code on code pen

下面是HTML代碼

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Monster</title> 
</head> 
<body> 
    <canvas id="canvas" width="900" height="800" style="light-grey; border: 1px solid black"> 
    Your browser does not support canvas 
    </canvas> 
</body> 
</html> 

這裏是JavaScript代碼

window.onload = function(){ 

var canvas = document.getElementById('canvas'); 
var ctx = canvas.getContext('2d'); 
var x = 0; 
var y = 0; 
var width = 0; 
var height = 0; 
var radius = 0; 

var squareLength = 450; 

ctx.save(); 
ctx.beginPath(); 
ctx.fillStyle = '#33b262'; 
//Translate to the center of the canvas 
ctx.translate(x+ 450, y+ 350); 
ctx.rotate(Math.PI /4); 
ctx.translate(x+ (-(squareLength/2)), y+ (- (squareLength/2))); 
ctx.fillRect(x + 0,y+ 0, width + squareLength, height+ 
squareLength); 
ctx.restore(); 
ctx.closePath(); 

// eye 
ctx.fillStyle = 'white'; 
ctx.beginPath(); 
ctx.arc(x + 450, y+ 210, radius+ 75, 0, 2 * Math.PI, false); 
ctx.closePath(); 
ctx.fill(); 

// eye black filling 
ctx.fillStyle = 'black'; 
ctx.beginPath(); 
ctx.arc(x + 450, y+ 210, radius+ 17, 0, 2 * Math.PI, false); 
ctx.closePath(); 
ctx.fill(); 

//mouth 
ctx.beginPath(); 
ctx.restore(); 
ctx.translate(x+ 250,y+ 100); 
ctx.rect(x + 100,y+ 300, width + 200,height+ 70); 
ctx.fillStyle = 'black'; 
ctx.fill(); 
ctx.closePath(); 

//left tooth 
ctx.beginPath(); 
ctx.restore(); 
ctx.rect(x + 135,y+ 300, width + 30,height+ 30); 
ctx.fillStyle = 'white'; 
ctx.fill(); 
ctx.closePath(); 

//right tooth 
ctx.beginPath(); 
ctx.restore(); 
ctx.rect(x + 237,y+ 300, width + 30,height+ 30); 
ctx.fillStyle = 'white'; 
ctx.fill(); 
ctx.closePath(); 

//bottom tooth 
ctx.beginPath(); 
ctx.restore(); 
ctx.rect(x + 185,y+ 340, width + 30,height+ 30); 
ctx.fillStyle = 'white'; 
ctx.fill(); 
ctx.closePath(); 

//left leg 
ctx.beginPath(); 
ctx.fillStyle = '#800000'; 
ctx.moveTo(x + 303, y+ 465); 
ctx.lineTo(x + 335, y+ 433); 
ctx.lineTo(x + 335, y+ 615); 
ctx.lineTo(x + 303, y+ 615); 
ctx.fill(); 
ctx.closePath(); 

//right leg 
ctx.beginPath(); 
ctx.fillStyle = '#800000'; 
ctx.moveTo(x + 97, y+ 465); 
ctx.lineTo(x + 65, y+ 433); 
ctx.lineTo(x + 65, y+ 615); 
ctx.lineTo(x + 97, y+ 615); 
ctx.fill(); 
ctx.closePath(); 

//right shoe 
ctx.fillStyle = '#330000'; 
ctx.beginPath(); 
ctx.arc(x + 319, y+ 660, radius+ 65, 0, 1 * Math.PI, true); 
ctx.closePath(); 
ctx.fill(); 

//right shoe 
ctx.fillStyle = '#330000'; 
ctx.beginPath(); 
ctx.arc(x + 79, y+ 660, radius+ 65, 0, 1 * Math.PI, true); 
ctx.closePath(); 
ctx.fill(); 
}; 

回答

0

可以使用canvas.scale方法爲這種目的 https://www.w3schools.com/tags/canvas_scale.asp 我包將我的繪圖代碼放到一個函數中,並在其開始處添加一條加線:

 

    function drawShape(scalewidth,scaleheight) { 
     ctx.scale(scalewidth,scaleheight); 
     ... 
    } 

然後用一些價值觀稱之爲:

 

    drawShape(0.5, 0.5);