D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
yonitru
Full window
Github gist
canvas_doubleBuffering
<!DOCTYPE html> <html> <head> <title>canvas 26</title> <style type="text/css"> #can1 { border:dotted black 1px; } </style> <script> var snowArr = []; var maxSnow = 200; var canvas = null; var ctx = null; var buffCanvas = null; var buffCtx = null; var interv = null; var interv2 = null; /*constructor to Snow object*/ function Snow() { this.x = Math.round(Math.random() * ctx.canvas.width); this.y = -10;//above the top of the canvas this.drift = Math.random(); this.speed = Math.round(Math.random() * 5)+1;//the +1 is to avoid 0 this.width = (Math.random() * 3)+2;//width is between 2 and 5 this.height = this.width; } window.onload = function () { canvas = document.getElementById('can1'); ctx = canvas.getContext('2d'); buffCanvas = document.createElement("canvas"); buffCtx = buffCanvas.getContext('2d'); buffCtx.canvas.width = ctx.canvas.width; buffCtx.canvas.height = ctx.canvas.height; interv = setInterval(addSnow2Arr,200); Draw(); interv2 = setInterval(animate,30); } function addSnow2Arr() { snowArr[snowArr.length] = new Snow(); if (snowArr.length == maxSnow) clearInterval(interv); } function animate() { Update();//changing parameters values Draw();//moving snow objects and copying to the real canvas } function Update() { for (var i=0; i<snowArr.length; i++) { if(snowArr[i].y < ctx.canvas.height) { snowArr[i].y += snowArr[i].speed; if (snowArr[i].y > ctx.canvas.height) snowArr[i].y = -5; snowArr[i].x += snowArr[i].drift; if(snowArr[i].x > ctx.canvas.width) snowArr[i].x = 0; } } } function Draw() { ctx.save(); //create a clipping region buffCtx.beginPath(); buffCtx.fillStyle = "#d8e3e8"; buffCtx.fillRect(0,0,buffCanvas.width,buffCanvas.height); buffCtx.arc(buffCanvas.width/2, buffCanvas.height/2,buffCanvas.height * 0.4, 0, 2*Math.PI); buffCtx.clip(); coverBgr(); for (var i=0; i<snowArr.length; i++) { if(snowArr[i].y < ctx.canvas.height) { buffCtx.fillStyle = "white"; buffCtx.fillRect(snowArr[i].x, snowArr[i].y, snowArr[i].width, snowArr[i].height); } } //copy the entire rendered img from the buffer canvas to the visible canvas on screen ctx.drawImage(buffCanvas, 0,0, buffCanvas.width, buffCanvas.height); ctx.restore(); } function coverBgr() { buffCtx.fillStyle = "#1e3d6c"; buffCtx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height); } function onCanvasClick() { //rectX = 0; clearInterval(interv); clearInterval(interv2); } </script> </head> <body> <div> <header> <h1>canvas 26</h1> </header> <div> <canvas id="can1" onclick="onCanvasClick()" width="600" height="400"> Fallback Content </canvas> </div> <footer> <p>© Copyright by yonit rusho</p> </footer> </div> </body> </html>