I can't completely clear the transformed recta

2019-08-10 05:41发布

问题:

This code can't completely clear the transformed rectangle in canvas element. How can i completely clear?

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

context.transform(1, 0.5, 0, 1, canvas.width / 2 , canvas.height);
context.fillStyle = 'red';
context.fillRect(20, 20, 200, 100);
context.clearRect(20, 20, 200, 100);

I can clear transformed rectangle by following code

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var x = 20;
var y = 20;
var width = 200;
var height = 100;

context.transform(1, 0.5, 0, 1, canvas.width / 2 , canvas.height / 2);
context.fillStyle = 'red';
context.fillRect(x, y, width, height);
context.clearRect(x, y - 1, width, height + 2);

I move up clear rectangle to top 1px and increase 2px wide to clear remaining border.

This code works well. But it is short term solution!

回答1:

I encountered this as well. This is caused by the anti-aliasing which is applied to the initial shape. It works with shapes which do not use anti-aliasing, such as rectangles when you don't transform your canvas. The only solution I found is to call clearRectangle with a shape that is slightly taller (about 1-2 pixels each side).