Reputation: 329
So I was playing around with canvas today and created a little script that places a button graphic when the user clicks on the screen. However, it has a strange glitch: On the initial click, the lines appear to be dark gray, turning solid black on the following click.
Does anybody know why that may be?
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();
});
Upvotes: 1
Views: 827
Reputation:
You need to use the beginPath()
method or the lines will accumulate for each time you call stroke()
on them. beginPath()
will reset the path object:
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();
}
Upvotes: 3