简体   繁体   中英

Canvas moving shadow after clearRect

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM