-
Notifications
You must be signed in to change notification settings - Fork 3
/
HTML5 - Beginners - objectDeepClone.html
71 lines (59 loc) · 1.51 KB
/
HTML5 - Beginners - objectDeepClone.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<!DOCTYPE html>
<html>
<head>
<meta charsetp="UTF-8">
<meta name="viewport" content="width=device-width" />
</head>
<body bgcolor="black">
<style>#myCanvas {touch-action: none;}</style>
<canvas id="myCanvas" width="320" height="240" style="border:0px solid #d3d3d3;">
Use different browser.
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// arrays in objects need
// to be all be cloned
// individually. this is
// a deep clone. if you
// only clone the main
// object. then the arrays
// inside these cloned objects
// all share the same memory
// (overwrite)
// create a object with
// a empty array.
const zewa1 = {
cook:10,
carrot:[]
}
// add 3 values the the object
// array
zewa1.carrot.push(1);
zewa1.carrot.push(2);
zewa1.carrot.push(3);
// create a clone from
// our previous object
const zewa2 = {...zewa1};
// create a clone from the array
// in the object(deep copy)
zewa2.carrot = {...zewa1.carrot};
// modify the array in the (deep)
// cloned object.
zewa2.carrot[0] = 10;
gameloop=setInterval(doGameLoop,16);
function doGameLoop(){
myCanvas.height = window.innerHeight*.98;
myCanvas.width = window.innerWidth*.96;
ctx.fillStyle="rgb(0,0,0)";
ctx.fillRect(0,0,c.width,c.height);
ctx.fillStyle="rgb(255,255,255)";
ctx.fillText("A javascript/html example.",10,10);
// draw our carrats object array
// you see both are unique
ctx.fillText(zewa1.carrot[0],10,30);
ctx.fillText(zewa2.carrot[0],10,50);
}
</script>
</body>
</html>