Hosting Solutions
mobile_logo Table of Contents

Fill and Stroke Styles Color Gradient Pattern

In this second exercise we will be covering the fill and stroke styles we can apply to fills and strokes on our canvas. Learn about creating gradient fills, pattern fills and color settings. <!DOCTYPE html> <html> <head> <style> body{ margin:40px; background:#666; } #my_canvas{ background:#FFF; border:#000 1px solid; } </style> <script> var leather = new Image(); leather.src = "leather.jpg"; function draw(){ var ctx = document.getElementById('my_canvas').getContext('2d'); // alert(" | "+ctx.canvas.width+" | "+ctx.canvas.height); // fillStyle = color || hex || rgba() || gradient || pattern // createLinearGradient(x0, y0, x1, y1) // createRadialGradient(x0, y0, r0, x1, y1, r1) // createPattern(Image_Resource, repeat_setting) var g1 = ctx.createLinearGradient(0, 0, 200, 0); g1.addColorStop(0,"magenta"); g1.addColorStop(0.5,"yellow"); g1.addColorStop(1,"black"); ctx.fillStyle = g1; ctx.strokeStyle = "red"; ctx.lineWidth = 10; ctx.fillRect(0, 0, 200, 200); ctx.strokeRect(0, 0, 200, 200); var g2 = ctx.createRadialGradient(350, 100, 0, 350, 100, 200); g2.addColorStop(0,"magenta"); g2.addColorStop(0.5,"yellow"); g2.addColorStop(1,"black"); ctx.fillStyle = g2; ctx.fillRect(250,0,200,200); ctx.strokeRect(250,0,200,200); var pattern = ctx.createPattern(leather, "repeat"); ctx.fillStyle = pattern; ctx.fillRect(0,250,200,200); ctx.lineWidth = 20; ctx.strokeStyle = g1; ctx.strokeRect(0,250,200,200); ctx.fill(); } window.onload = draw; </script> </head> <body> <canvas id="my_canvas" width="700" height="500"></canvas> </body> </html>

JavaScript Videos

Canvas Programming

2D Context Object and Rectangle MethodsFill and Stroke Styles Color Gradient PatternLine Styles for Lines and StrokesBuilding and Drawing PathsDrawing Images and VideosDrawing Text on CanvasRendering Shadows on CanvasCanvas Transformation EffectsPixel Manipulation on CanvasCompositing on the CanvasDynamic Centering and Alignment on the CanvasCanvas Animation and App InitializationObject Oriented Assets OOP on CanvasDetect Mouse Coordinates on CanvasAnimated Background Layers on Canvas TutorialKeyboard Control and MovementJSON Object Arrays and Loops on CanvasHit Detection Mouse Touch Over Object ArraysCollision Detection Hit Game EnemiesParticle Effect System Tutorial Snow Falling AnimationInteractive Canvas Imaging Applications JavaScript PHP TutorialCircular Progress Loader Canvas JavaScript Programming Tutorial