JAVASCRIPT Interaktivitet
Bibliotek
Använder samma bibliotek som i "Javascript Bibliotek" plus att funktionen "snowMan" är instoppad i biblioteket också.
Automatisk uppdatering
Vi kan använda två färdiga javaskript-funktioner, setInterval eller setTimeout.
För att rita så måste vi använda funktionerna i javascript. En hel testfil skulle kunna se ut så här:
<html>
<head>
<meta charset="utf-8">
<title>Namnlöst dokument</title>
<style type="text/css">
#canvasContainer {
width: 502px;
margin-left: auto;
margin-right: auto;
}
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<div id="canvasContainer">
<canvas id="myCanvas" width="500px" height="500px"></canvas>
</div>
<script src="myLibrary2.js"></script>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
function updateCanvas () {
ctx.clearRect(0, 0, 500, 500);
snowMan(ctx,x,y);
x=x+5;
y=y+2;
}
var x=100, y=100;
var updateTime=50; //millisekunder
var timer = setInterval(updateCanvas, updateTime);
</script>
</body></html>
Tangentstyrning
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
window.addEventListener('keydown', keyListener);
// OBS! Bara funktionens namn
function keyListener(evt){
if(evt.keyCode==37 ){
//keyCode 37 is left arrow
x -= 20;
}
if(evt.keyCode==39 ){
//keyCode 39 is right arrow
x += 20;
}
if(evt.keyCode==38 ){
//keyCode 39 is up arrow
y -= 20;
}
if(evt.keyCode==40 ){
//keyCode 39 is down arrow
y += 20;
}
ctx.clearRect(0, 0, 500, 500);
snowMan(ctx,x,y);
}
var x=100, y=100;
snowMan(ctx,x,y);
</script>
Musstyrning
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
c.addEventListener('mousedown', mouseListener);
function mouseListener(event){
//Coordinates relative to the document: pageX/pageY
var xPage = event.pageX;
var yPage = event.pageY;
//Returns the left position of an object relative to the left side
// of its offsetParent element, in pixels.
//offsetParent is the closest ancestor element in the DOM hierarchy
// from which the position of the current element is calculated.
var xMouse = xPage - c.offsetLeft;
var yMouse = yPage - c.offsetTop;
//alert("Koordinater i canvas-objektet "+xMouse+" "+yMouse);
//ctx.clearRect(0, 0, 500, 500);
snowMan(ctx,xMouse,yMouse);
}
var x=100, y=100;
snowMan(ctx,x,y);
</script>
Källor
http://javascript.info/tutorial
http://cheatsheetworld.com/programming/html5-canvas-cheat-sheet/