Reputation: 1412
I am new to HTML5 and start learning canvas.
Currently, I am using canvas to make some objects rotate. The rectangle I created do move, however, I suffer from a problem, after the object move, some shadows remain as you can see from the image I captured.
I just want to have the rectangle, and not including the blue background clumsy stuff. I try to use different browsers to view this HTML5 document, but same problem comes out. Is this a problem of my computer, or is it a problem of the code? If so, how can I solve it?
I have also attached my source code of rotating rectangle example in jsFiddle: http://jsfiddle.net/hphchan/ogoj9odf/1/
Here is my key code:
In Javascript:
function canvaScript() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.translate(200, 200); // fix the origin as center of the canvas
rotating(context);
}
function rotating(context) {
context.clearRect(-50, -100, 100, 200); // why boundaries, shadows exist??
context.rotate(Math.PI/180);
context.fillStyle = '#0000FF';
context.fillRect(-50, -100, 100, 200);
setTimeout(function() {rotating(context)}, 100);
}
In HTML
<body onload="canvaScript()">
<canvas id="myCanvas" width="400" height="400"></canvas>
</body>
Thanks for answering.
Upvotes: 1
Views: 519
Reputation: 137016
This problem probably comes from the anti-aliasing.
You can see it by clearing directly after you drawn your rotated shape :
function canvaScript() {
var context = canvas.getContext('2d');
context.translate(200, 200); // fix the origin as center of the canvas
context.rotate(Math.PI/4);
rotating(context);
}
function rotating(context) {
context.fillStyle = '#0000FF';
context.fillRect(-50, -100, 100, 200);
context.clearRect(-50, -100, 100, 200);
}
canvaScript();
<canvas id="canvas" width="400" height="400"></canvas>
So one solution to workaround this is to clear a slightly larger clearRect
than the rect you just drawn.
function canvaScript() {
var context = canvas.getContext('2d');
context.translate(200, 200); // fix the origin as center of the canvas
rotating(context);
}
function rotating(context) {
// clear one extra pixel in all directions
context.clearRect(-51, -101, 102, 202);
context.rotate(Math.PI/180);
context.fillStyle = '#0000FF';
context.fillRect(-50, -100, 100, 200);
setTimeout(function() {rotating(context)}, 100);
}
canvaScript();
<canvas id="canvas" width="400" height="400"></canvas>
Upvotes: 2