[英]Context.clearRect in Canvas doesn't work
如果我得到一張圖片並想將其繪制到右側,則可以使用。 但是當我添加clearRect()
,圖片消失了。 如何使用正確的方法使用類似的代碼,以使clearRect()
起作用?
這是我的代碼:
<html>
<head>
<style>
#canvas_id{
border:1px solid red;
}
</style>
</head>
<body>
<canvas id="canvas_id"></canvas>
<script>
var canvas = document.getElementById( "canvas_id" );
var Context = canvas.getContext( "2d" );
var x1 = 10;
var x2 = 10;
var img = new Image();
img.src = "example.jpg";
img.onload = function(){ Context.drawImage( img, x1, x2,20,20); }
draw();
function draw(){
window.requestAnimationFrame(draw);
Context.clearRect(0,0,innerWidth,innerHeight);
var Img = new Image();
Img.src = "example.jpg";
Img.onload = function(){ Context.drawImage( Img, x1, x2,20,20); }
x1 = x1 +1;
}
</script>
</body>
如果我使用fillRect()
代替圖像而不是圖像來處理矩形,則代碼有效。
僅加載一次圖像。
requestAnimationFrame
回調將在下一次繪制到屏幕之前被調用。 這是代碼中發生的情況的示意圖:
clearRect start_to_load_Img || ... img.loaded=>drawImage ... clearRect start_to_load_Img || etc.
^ ^
render new frame to screen render new frame to screen
如您所見,每次圖像加載在兩幀之間。 但是在下一幀傳遞到屏幕之前,您已經清除了它。
所以固定代碼看起來像
// load your image only once
var img = new Image();
img.src = "example.jpg";
draw();
function draw(){
window.requestAnimationFrame(draw);
Context.clearRect(0,0,innerWidth,innerHeight);
if(img.naturalWidth) { // check it has loaded
Context.drawImage(img, x1, x2,20,20);
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.