Custom drawn 3d object on canvas (html5). Today’s lesson very interesting, we’ll learn how to create 3D objects using HTML5. This is our first lesson on the practice HTML5. In this tutorial we will make a quadrangular star. Which will rotate around its axis. Read more.
Here are samples and downloadable package:
[sociallocker]
[/sociallocker]
Ok, download the example files and lets start coding !
Step 1. HTML
As usual, we start with the HTML. This is source code of our sample:
index.html
04 | <title>3D Canvas HTML5</title> |
05 | <link rel="stylesheet" type="text/css" href="css/main.css" /> |
06 | <script type="text/javascript" src="js/main.js"></script> |
10 | <canvas id="star_object" style="border:1px solid black;"><p class="noCanvas">Sorry, your browser don`t support Canvas in HTML5</canvas> |
Very easy, isn`t it? I just draw here our canvas object. Main drawing will in javascript of course.
Step 2. CSS
Here are single CSS file with all necessary styles (this is just styles for our example layout):
css/main.css
1 | body{background:#eee;margin:0;padding:0} |
2 | .example{background:#FFF;width:500px;border:1px #000 solid;margin:20px auto;padding:15px;-moz-border-radius: 3px;-webkit-border-radius: 3px} |
Step 3. JS
Here are our main JS code:
js/main.js
02 | var iCanvasWidth = 500; |
03 | var iCanvasHeight = 500; |
10 | if (x + dx > iStarSize/2 || x + dx < -iStarSize/2) |
19 | context.clearRect(0, 0, iCanvasWidth, iCanvasWidth); |
22 | context.translate( iStarSize * 1.5, iStarSize * 1.5 ); |
24 | context.fillStyle = '#bbb'; |
25 | context.strokeStyle = '#000'; |
26 | context.lineWidth = 2; |
32 | context.moveTo( 0, -iStarSize ); |
33 | context.lineTo( iStarSize / 10 - x / 5, - iStarSize / 5 ); |
34 | context.lineTo( iStarSize / 2 - x, 0 ); |
35 | context.lineTo( iStarSize / 10 - x / 5, iStarSize / 5 ); |
36 | context.lineTo( 0, iStarSize ); |
37 | context.lineTo( -iStarSize / 10 + x / 5, iStarSize / 5 ); |
38 | context.lineTo( -iStarSize / 2 + x, 0 ); |
39 | context.lineTo( -iStarSize / 10 + x / 5, - iStarSize / 5 ); |
40 | context.lineTo( 0, -iStarSize ); |
42 | context.shadowOffsetX = 10; |
43 | context.shadowOffsetY = 10; |
44 | context.shadowBlur = 4; |
45 | context.shadowColor = 'rgba(180, 180, 180, 0.8)'; |
52 | context.font = '12px Verdana'; |
53 | context.fillStyle = '#000'; |
54 | context.fillText('x: ' + x + '; y: ' + y, 10, 15); |
55 | context.fillText('dx: ' + dx + '; dy: ' + dy, 10, 30); |
57 | window.onload = function(){ |
58 | canvas = document.getElementById('star_object'); |
60 | canvas.width = iCanvasWidth; |
61 | canvas.height = iCanvasWidth; |
62 | context = canvas.getContext('2d'); |
I tried to comment quite any row of my code. You should just point attention what I doing inside ‘render’ function.
Conclusion
I hope our first lesson about working with HTML5 showed you an interesting, if you have any suggestions, or you just have to say – we are glad to hear it. Good luck!