SlideShare a Scribd company logo
DRAWING ON CANVAS

     chapter 6
Javascript + canvas

    - Drawing a Logo



    - Graphing Statistics with RGraph
 

The Canvas Element

<canvas id="my_canvas" width="150" height="150"> 
 Fallback content here 
</canvas>

can't use css
 

var canvas = document.getElementById('my_canvas');
if (canvas.getContext){
    var context = canvas.getContext('2d');
}else{

}
canvas_simple_drawing.html

var canvas = document.getElementById('my_canvas'); 
 if (canvas.getContext){ 
 var context = canvas.getContext('2d'); 
  context.fillStyle = "rgb(200,0,0)"; 
  context.fillRect (10, 10, 100, 100); 
  context.fillStyle = "rgb(0,0,200)"; 
  context.fillRect (30, 30, 100, 100); 
  context.strokeStyle = "rgb(200,0,0)"; 
  context.lineWidth = 2; context.beginPath(); context.moveTo
(0, 0); context.lineTo(100, 100); context.stroke(); context.
closePath();}........
Drawing the logo

string of text, an angeld path, a squeare, a triangle

Adding Text 
   c o n t e x t . f o n t = ' i t a l i c 4 0 p x s a n s - s e r i f ' ;
   c o n t e x t . t e x t B a s e l i n e = ' t o p ' ;
   c o n t e x t . f i l l T e x t ( ' A w e s o m e C o ' , 6 0 , 0 ) ;
Drawing the Logo

Drawing lines
    c o n t e x t   .   lineWidth=2;
    c o n t e x t   .   beginPath();
    c o n t e x t   .   moveTo(0,40);
    c o n t e x t   .   lineTo(30,0);
    c o n t e x t   .   lineTo(60,40);
    c o n t e x t   .   lineTo(285,40);
    c o n t e x t   .   stroke();
    c o n t e x t   .   c l o s e P a t h ( ) 
Drawing the Logo

Moving the Origin
    c o n t e x t . s a v e ( ) ;
    c o n t e x t . t r a n s l a t e ( 2 0 , 2 0 ) ;
    c o n t e x t . f i l l R e c t ( 0 , 0 , 2 0 , 2 0 ) ;
Drawing the Logo

Drawing a triangle
    c o n t e x t . f i l l S t y l e = ' # f f f '
    c o n t e x t . s t r o k e S t y l e = ' # f f f ' ;
    c o n t e x t . l i n e W i d t h = 2 ;
    c o n t e x t . b e g i n P a t h ( ) ;
    c o n t e x t . m o v e T o ( 0 , 2 0 ) ;
    c o n t e x t . l i n e T o ( 1 0 , 0 ) ;
    c o n t e x t . l i n e T o ( 2 0 , 2 0 ) ;
    c o n t e x t . l i n e T o ( 0 , 2 0 ) ;
    c o n t e x t . f i l l ( ) ;
    c o n t e x t . c l o s e P a t h ( ) ;
    c o n t e x t . r e s t o r e ( ) ;
Drawing the Logo

AddingColors
// context.fillStyle = "#f00";
// context.strokeStyle = "#f00";
var gradient = context.createLinearGradient(0, 0, 0, 40);
gradient.addColorStop(0, '#a00'); // red
gradient.addColorStop(1, '#f00'); // red
context.fillStyle = gradient;
context.strokeStyle = gradient;
Falling back

Google released a library called ExplorerCanvas

<scriptsrc="javascripts/excanvas.js">
</script>
Graphing Statistics with RGraph




<canvas width="500" height="250" id="test">[no canvas
support]</canvas> 

<script type="text/javascript" charset="utf-8"> 
 var bar = new RGraph.Bar('test', [50,25,15,10]); bar.Set
('chart.gutter', 50); bar.Set('chart.colors', ['red']); bar.Set
('chart.title', "A bar graph of my favorite pies"); bar.Set('chart.
labels', ["Banana Creme", "Pumpkin", "Apple", "Cherry"]); 
 bar.Draw(); 
 </script>
 

Describing Data with HTML

<div id="graph_data"> <h1>Browser share for this site</h1>
<ul> <li> <p data-name="Safari 4" data-percent="15"> Safari 4 -
15% </p> </li> <li> <p data-name="Internet Explorer" data-
percent="55"> Internet Explorer - 55% </p> </li> <li> <p data-
name="Firefox" data-percent="14"> Firefox - 14% </p> </li>
<li> <p data-name="Google Chrome" data-percent="16">
Google Chrome - 16% </p> </li> </ul> </div>
 

load libraries
<script type="text/javascript" charset="utf-8" src="http:
//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
> </script> 
<script src="javascripts/RGraph.common.js" ></script> <script
src="javascripts/RGraph.bar.js" ></script>
 

Turning Our HTML into a Bar Graph

function canvasGraph(){ var title = $('#graph_data h1').text();
var labels = $("#graph_data>ul>li>p[data-name]").map
(function(){ return $(this).attr("data-name"); });
var percents = $("#graph_data>ul>li>p[data-percent]").map
(function(){ return parseInt($(this).attr("data-percent")); });
var bar = new RGraph.Bar('browsers', percents); bar.Set
('chart.gutter', 50); bar.Set('chart.colors', ['red']); bar.Set
('chart.title', title); bar.Set('chart.labels', labels); bar.Draw();
}
Displaying Alternative Content


var canvas = document.getElementById('browsers'); 
 if (canvas.getContext)
{ 
 $('#graph_data').hide(); 
 canvasGraph(); 
 }
Falling back

function divGraph(barColor, textColor, width, spacer,
lblHeight)
{ 
 $('#graph_data ul').hide(); 
 var container = $("#graph_data"); 
 container.css( { "display" : "block", "position" : "relative",
"height": "300px"} );
$("#graph_data>ul>li>p").each(function(i){ 
    var bar = $("<div>" + $(this).attr("data-percent") + "%
</div>"); 
   var label = $("<div>" + $(this).attr("data-name") +
"</div>");               var commonCSS = { "width": width + "px",
"position" : "absolute", "left" : i * (width + spacer) + "px"}; var
barCSS = { "background-color" : barColor, "color" : textColor,
The Future

 

More Related Content

PDF
An Introduction to Tinkerpop
DOCX
Theme verdadeiro
PDF
Pointer level 2
DOCX
Ping pong game
PDF
[SI] Ada Lovelace Day 2014 - Tampon Run
PDF
DOCX
A simple snake game project
DOCX
Hangman Game Programming in C (coding)
An Introduction to Tinkerpop
Theme verdadeiro
Pointer level 2
Ping pong game
[SI] Ada Lovelace Day 2014 - Tampon Run
A simple snake game project
Hangman Game Programming in C (coding)

What's hot (18)

PDF
Programa expresiones regulares
PDF
Worth the hype - styled components
PDF
Perlで実装されたLINE NEWSの裏側
TXT
C code
PPTX
Paperjs presentation
PDF
Random. Kinda.
DOCX
Plot3D Package and Example in R.-Data visualizat,on
TXT
Zebra
PPTX
Paperjs presentation
PDF
Processing資料(8) 文字
PPTX
Pointer level 2
PDF
Tablas relaciones proyecto Laravel
PDF
Exploring Canvas
PDF
Cpd lecture im 207
PPTX
Oh, you’re the NY times guy
TXT
Formato encuesta
PDF
画像Hacks
Programa expresiones regulares
Worth the hype - styled components
Perlで実装されたLINE NEWSの裏側
C code
Paperjs presentation
Random. Kinda.
Plot3D Package and Example in R.-Data visualizat,on
Zebra
Paperjs presentation
Processing資料(8) 文字
Pointer level 2
Tablas relaciones proyecto Laravel
Exploring Canvas
Cpd lecture im 207
Oh, you’re the NY times guy
Formato encuesta
画像Hacks
Ad

Viewers also liked (7)

PPTX
7장매크로
PPT
2.2.4 순환목록
PPT
1.4.2 코루틴연습문제
PPT
Clojure in the Wild
PPTX
클로저
PPT
8.다중메서드
PPTX
Clojure Chapter.6
7장매크로
2.2.4 순환목록
1.4.2 코루틴연습문제
Clojure in the Wild
클로저
8.다중메서드
Clojure Chapter.6
Ad

Similar to Drawing on canvas (20)

PPT
HTML5 Canvas
PPTX
HTML 5_Canvas
PPTX
Advanced html5 diving into the canvas tag
PPTX
Css5 canvas
PPTX
HTML 5 Canvas & SVG
PPTX
canvas_1.pptx
PDF
Html5 canvas notes for professionals
PDF
HTML5 Canvas - The Future of Graphics on the Web
PPTX
HTML5 Canvas - Basics.pptx
KEY
Exploring Canvas
PPTX
Html5 canvas
PDF
Introduction to HTML5 Canvas
PDF
How to build a html5 websites.v1
PPTX
canvas.pptx
PDF
Html5 canvas
PPT
Html5workshop
PPT
PPT
PPTX
JavaScript Canvas
PDF
Intro to HTML5 Canvas
HTML5 Canvas
HTML 5_Canvas
Advanced html5 diving into the canvas tag
Css5 canvas
HTML 5 Canvas & SVG
canvas_1.pptx
Html5 canvas notes for professionals
HTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - Basics.pptx
Exploring Canvas
Html5 canvas
Introduction to HTML5 Canvas
How to build a html5 websites.v1
canvas.pptx
Html5 canvas
Html5workshop
JavaScript Canvas
Intro to HTML5 Canvas

More from suitzero (7)

PPT
The gravitational N -body pro
PPT
xUnitTestPattern/chapter16
PPT
HolubOnPatterns/chapter3_3
PPT
3장 자동적으로 움직이는 게임 에이전트 생성법_2
PPT
3장 자동적으로 움직이는 게임 에이전트 생성법
PPT
부울 대수와 컴퓨터 논리
PPT
프리젠테이션-제목없음
The gravitational N -body pro
xUnitTestPattern/chapter16
HolubOnPatterns/chapter3_3
3장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법
부울 대수와 컴퓨터 논리
프리젠테이션-제목없음

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
A Presentation on Artificial Intelligence
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Empathic Computing: Creating Shared Understanding
PPT
Teaching material agriculture food technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
PPTX
TLE Review Electricity (Electricity).pptx
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Spectroscopy.pptx food analysis technology
PPTX
OMC Textile Division Presentation 2021.pptx
PPTX
1. Introduction to Computer Programming.pptx
Encapsulation theory and applications.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Per capita expenditure prediction using model stacking based on satellite ima...
Building Integrated photovoltaic BIPV_UPV.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Encapsulation_ Review paper, used for researhc scholars
A Presentation on Artificial Intelligence
A comparative analysis of optical character recognition models for extracting...
Empathic Computing: Creating Shared Understanding
Teaching material agriculture food technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
A comparative study of natural language inference in Swahili using monolingua...
TLE Review Electricity (Electricity).pptx
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Spectroscopy.pptx food analysis technology
OMC Textile Division Presentation 2021.pptx
1. Introduction to Computer Programming.pptx

Drawing on canvas

  • 1. DRAWING ON CANVAS chapter 6
  • 2. Javascript + canvas     - Drawing a Logo     - Graphing Statistics with RGraph
  • 3.   The Canvas Element <canvas id="my_canvas" width="150" height="150">   Fallback content here  </canvas> can't use css
  • 4.   var canvas = document.getElementById('my_canvas'); if (canvas.getContext){     var context = canvas.getContext('2d'); }else{ }
  • 5. canvas_simple_drawing.html var canvas = document.getElementById('my_canvas');   if (canvas.getContext){   var context = canvas.getContext('2d');    context.fillStyle = "rgb(200,0,0)";    context.fillRect (10, 10, 100, 100);    context.fillStyle = "rgb(0,0,200)";    context.fillRect (30, 30, 100, 100);    context.strokeStyle = "rgb(200,0,0)";    context.lineWidth = 2; context.beginPath(); context.moveTo (0, 0); context.lineTo(100, 100); context.stroke(); context. closePath();}........
  • 6. Drawing the logo string of text, an angeld path, a squeare, a triangle Adding Text     c o n t e x t . f o n t = ' i t a l i c 4 0 p x s a n s - s e r i f ' ;    c o n t e x t . t e x t B a s e l i n e = ' t o p ' ;    c o n t e x t . f i l l T e x t ( ' A w e s o m e C o ' , 6 0 , 0 ) ;
  • 7. Drawing the Logo Drawing lines     c o n t e x t . lineWidth=2;     c o n t e x t . beginPath();     c o n t e x t . moveTo(0,40);     c o n t e x t . lineTo(30,0);     c o n t e x t . lineTo(60,40);     c o n t e x t . lineTo(285,40);     c o n t e x t . stroke();     c o n t e x t . c l o s e P a t h ( ) 
  • 8. Drawing the Logo Moving the Origin     c o n t e x t . s a v e ( ) ;     c o n t e x t . t r a n s l a t e ( 2 0 , 2 0 ) ;     c o n t e x t . f i l l R e c t ( 0 , 0 , 2 0 , 2 0 ) ;
  • 9. Drawing the Logo Drawing a triangle     c o n t e x t . f i l l S t y l e = ' # f f f '     c o n t e x t . s t r o k e S t y l e = ' # f f f ' ;     c o n t e x t . l i n e W i d t h = 2 ;     c o n t e x t . b e g i n P a t h ( ) ;     c o n t e x t . m o v e T o ( 0 , 2 0 ) ;     c o n t e x t . l i n e T o ( 1 0 , 0 ) ;     c o n t e x t . l i n e T o ( 2 0 , 2 0 ) ;     c o n t e x t . l i n e T o ( 0 , 2 0 ) ;     c o n t e x t . f i l l ( ) ;     c o n t e x t . c l o s e P a t h ( ) ;     c o n t e x t . r e s t o r e ( ) ;
  • 10. Drawing the Logo AddingColors // context.fillStyle = "#f00"; // context.strokeStyle = "#f00"; var gradient = context.createLinearGradient(0, 0, 0, 40); gradient.addColorStop(0, '#a00'); // red gradient.addColorStop(1, '#f00'); // red context.fillStyle = gradient; context.strokeStyle = gradient;
  • 11. Falling back Google released a library called ExplorerCanvas <scriptsrc="javascripts/excanvas.js"> </script>
  • 12. Graphing Statistics with RGraph <canvas width="500" height="250" id="test">[no canvas support]</canvas>  <script type="text/javascript" charset="utf-8">   var bar = new RGraph.Bar('test', [50,25,15,10]); bar.Set ('chart.gutter', 50); bar.Set('chart.colors', ['red']); bar.Set ('chart.title', "A bar graph of my favorite pies"); bar.Set('chart. labels', ["Banana Creme", "Pumpkin", "Apple", "Cherry"]);   bar.Draw();   </script>
  • 13.   Describing Data with HTML <div id="graph_data"> <h1>Browser share for this site</h1> <ul> <li> <p data-name="Safari 4" data-percent="15"> Safari 4 - 15% </p> </li> <li> <p data-name="Internet Explorer" data- percent="55"> Internet Explorer - 55% </p> </li> <li> <p data- name="Firefox" data-percent="14"> Firefox - 14% </p> </li> <li> <p data-name="Google Chrome" data-percent="16"> Google Chrome - 16% </p> </li> </ul> </div>
  • 14.   load libraries <script type="text/javascript" charset="utf-8" src="http: //ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" > </script>  <script src="javascripts/RGraph.common.js" ></script> <script src="javascripts/RGraph.bar.js" ></script>
  • 15.   Turning Our HTML into a Bar Graph function canvasGraph(){ var title = $('#graph_data h1').text(); var labels = $("#graph_data>ul>li>p[data-name]").map (function(){ return $(this).attr("data-name"); }); var percents = $("#graph_data>ul>li>p[data-percent]").map (function(){ return parseInt($(this).attr("data-percent")); }); var bar = new RGraph.Bar('browsers', percents); bar.Set ('chart.gutter', 50); bar.Set('chart.colors', ['red']); bar.Set ('chart.title', title); bar.Set('chart.labels', labels); bar.Draw(); }
  • 16. Displaying Alternative Content var canvas = document.getElementById('browsers');   if (canvas.getContext) {   $('#graph_data').hide();   canvasGraph();   }
  • 17. Falling back function divGraph(barColor, textColor, width, spacer, lblHeight) {   $('#graph_data ul').hide();   var container = $("#graph_data");   container.css( { "display" : "block", "position" : "relative", "height": "300px"} ); $("#graph_data>ul>li>p").each(function(i){      var bar = $("<div>" + $(this).attr("data-percent") + "% </div>");     var label = $("<div>" + $(this).attr("data-name") + "</div>");               var commonCSS = { "width": width + "px", "position" : "absolute", "left" : i * (width + spacer) + "px"}; var barCSS = { "background-color" : barColor, "color" : textColor,