Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <canvas width="500" height="500"></canvas>
              
            
!

CSS

              
                canvas{
  background-color: #000;
}
              
            
!

JS

              
                const startTime = performance.now();
const durationTotal = 5000;

function drawRect(ctx,x,y){
  // 這就是很普通的畫一個方塊在指定座標的位置上
  // 假設長寬都是40
  const size = 20;
   // 設定填充色
  ctx.fillStyle="#fff";
  ctx.fillRect(x,y,size*2,size*2);
 
}

function animate(ctx){
  // 預設都先清除舊畫面然後重新畫一個在新位置的方塊
  let timeNow = performance.now() - startTime;
  //
  const speed = 0.05; //假設速度是0.05px/毫秒
  
  ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height)
  drawRect(ctx,speed*timeNow,50);
  
  // 在目前花費時間還沒超過總預設花費時間的狀況下就持續動作
  if(timeNow<durationTotal){
    // 告訴瀏覽器下一幀要做的動作, 可以想像成一個極短的setTimeout, delay時間大約是1/60秒
    // 這邊我們透過遞迴執行animate來繪製下一幀的畫面
     requestAnimationFrame(()=>{animate(ctx)})
  }
  else{
    return
  }
}


function draw(){
  const cvs = document.querySelector('canvas');
  const ctx = cvs.getContext('2d');
  animate(ctx);
}




(()=>{
  draw();
})()
              
            
!
999px

Console