所以今天我正在玩canvas,并创建了一个小脚本,当用户点击屏幕时会放置一个按钮图形。然而,它有一个奇怪的故障:在初始点击时,线条显示为深灰色,在下一次点击时变为纯黑色。
有人知道为什么会这样吗?
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();
});
答案 0 :(得分:2)
您需要使用beginPath()
方法,否则每次调用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();
}