2013-10-12 25 views
0

所以我今天玩帆布和創建一個小腳本,當用戶點擊屏幕時放置一個按鈕圖形。然而,它有一個奇怪的故障:在最初的點擊,線條看起來是深灰色,在下面的點擊變成純黑色。帆布線顯示更輕,然後更暗

有人知道爲什麼可能嗎?

jsfiddle

HTML:

<!DOCTYPE html> 
<html> 
    <head> 
     <link type="text/css" rel="stylesheet" href="paint.css" /> 
     <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
     <script type="text/javascript" src="paint.js"></script> 
    </head> 
    <body> 
     <div id="container"> 
      <canvas id="canvas" width="500px" height="500px">Not supported.</canvas> 
     </div> 
    </body> 
</html> 

CSS:

html, body { 
    border: 0; 
    padding: 0; 
    margin: 0; 

    height: 100%; 
    width: 100%; 
} 

#canvas { 
    border: 1px dotted black; 
} 

的Javascript:

var paint = { 

    init: function() { 
     var canvas = document.getElementById('canvas'), 
      ctx = canvas.getContext('2d'); 

     $(document).on('click', function(e) { 
      var x = e.clientX, 
       y = e.clientY; 

      paint.draw_button(ctx, x, y, 2, 15); 

     }); 
    }, 

    draw_button: function(ctx, x, y, scale, rad) { 
     scale = scale * 25.5, 
     rad = scale - rad; 

     ctx.moveTo(x-rad, y-scale); 
     ctx.lineTo(x+rad,y-scale); 
     ctx.bezierCurveTo(x+rad, y-scale, x+scale,y-scale, x+scale, y-rad); 
     ctx.lineTo(x+scale,y+rad); 
     ctx.bezierCurveTo(x+scale,y+rad, x+scale, y+scale, x+rad, y+scale); 
     ctx.lineTo(x-rad,y+scale); 
     ctx.bezierCurveTo(x-rad, y+scale, x-scale, y+scale, x-scale, y+rad); 
     ctx.lineTo(x-scale,y-rad); 
     ctx.bezierCurveTo(x-scale,y-rad, x-scale, y-scale, x-rad, y-scale); 

     ctx.stroke(); 
    }, 
}; 

$(function() { 
    paint.init(); 
}); 

回答

1

您需要使用beginPath()方法或林es會積累每次你打電話給他們stroke()beginPath()將重置路徑對象:

draw_button: function(ctx, x, y, scale, rad) { 
    scale = scale * 25.5, 
    rad = scale - rad; 

    ctx.beginPath(); /// here 

    ctx.moveTo(x-rad, y-scale); 
    ctx.lineTo(x+rad,y-scale); 
    ctx.bezierCurveTo(x+rad, y-scale, x+scale,y-scale, x+scale, y-rad); 
    ctx.lineTo(x+scale,y+rad); 
    ctx.bezierCurveTo(x+scale,y+rad, x+scale, y+scale, x+rad, y+scale); 
    ctx.lineTo(x-rad,y+scale); 
    ctx.bezierCurveTo(x-rad, y+scale, x-scale, y+scale, x-scale, y+rad); 
    ctx.lineTo(x-scale,y-rad); 
    ctx.bezierCurveTo(x-scale,y-rad, x-scale, y-scale, x-rad, y-scale); 

    ctx.stroke(); 
} 
+0

啊,我覺得自己像一個傻瓜哈哈。謝謝! –

+0

@tomc沒問題,我們都不時做簡單的錯誤:) – K3N