2017-04-24 95 views
0

我正在嘗試編寫一個函數,該函數可以在html畫布中繪製給定xy座標,寬度和高度的曲線矩形,但是當前我的腳本會輸出空白畫布。爲什麼代碼不能繪製矩形?Javascript - 繪製曲線矩形的函數

var c=document.getElementById(id); 
var ctx=c.getContext('2d'); 

function makeCurvedRect(x, y, w, h) { 
    ctx.beginPath(); 
    ctx.moveTo(x+10, y); 
    ctx.lineTo(x+w-10, y); 
    ctx.quadraticCurveTo(x+w, y, x+w, y+10); 
    ctx.lineTo(x+w, y+h-10); 
    ctx.quadraticCurveTo(x+w, y+h, x+w-10, y+h); 
    ctx.lineTo(x+10, y+h); 
    ctx.quadraticCurveTo(x, y+h, x, y+h - 10]); 
    ctx.lineTo(x, y+10); 
    ctx.quadraticCurveTo(x, y, x+10, y); 
    ctx.stroke(); 
} 

makeCurvedRect(162.5,40,175,175); 
+0

看來你在ctx.quadraticCurveTo(x,y +)行遇到語法錯誤h,x,y + h - 10]);讓我們刪除']'並重試 –

回答

2

這是因爲,你在這行

ctx.quadraticCurveTo(x, y+h, x, y+h - 10]); 
             ^this 

導致發生不必要的括號(])的代碼,打破

var c = document.getElementById('canvas'); 
 
var ctx = c.getContext('2d'); 
 

 
function makeCurvedRect(x, y, w, h) { 
 
    ctx.beginPath(); 
 
    ctx.moveTo(x + 10, y); 
 
    ctx.lineTo(x + w - 10, y); 
 
    ctx.quadraticCurveTo(x + w, y, x + w, y + 10); 
 
    ctx.lineTo(x + w, y + h - 10); 
 
    ctx.quadraticCurveTo(x + w, y + h, x + w - 10, y + h); 
 
    ctx.lineTo(x + 10, y + h); 
 
    ctx.quadraticCurveTo(x, y + h, x, y + h - 10); 
 
    ctx.lineTo(x, y + 10); 
 
    ctx.quadraticCurveTo(x, y, x + 10, y); 
 
    ctx.stroke(); 
 
} 
 
makeCurvedRect(60, 60, 175, 175);
canvas { 
 
    border: 1px solid black; 
 
}
<canvas id="canvas" width="300" height="300"></canvas>