简体   繁体   中英

I can't completely clear the transformed rectangle in <canvas>

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!

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).

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