Views Codehs: 2.3.9 Nested
// 5. Text nested inside Content var bodyText = new Text("This text is inside a nested view."); bodyText.setColor("#333333"); bodyText.setPosition(content.getX() + 15, content.getY() + 30); bodyText.setFont("12pt Arial"); add(bodyText);
function start() { // 1. Parent View (the main container) var parent = new Rectangle(300, 400); parent.setPosition(100, 100); parent.setColor("#E0E0E0"); // Light gray parent.setBorderWidth(2); parent.setBorderColor("black"); add(parent); // 2. Nested Child 1: Header Bar var header = new Rectangle(260, 50); header.setColor("#4A90E2"); // Blue header.setPosition(parent.getX() + 20, parent.getY() + 20); add(header); 2.3.9 nested views codehs
// Header child view (inside parent) var headerView = new Rectangle(260, 50); headerView.setColor("navy"); headerView.setPosition(parentView.getX() + 20, parentView.getY() + 20); add(headerView); This is the "nested" part. The text should sit inside the header view. Again, we calculate its position based on the header’s position. Nested Child 1: Header Bar var header =
var parentView = new Rectangle(300, 400); parentView.setPosition(50, 50); // Position on the canvas parentView.setColor("lightgray"); parentView.setBorderWidth(2); add(parentView); Now, create a child that sits inside the parent. The key is that its x and y are relative to the parent’s position . If the parent is at (50, 50), and you want the child at the top-left corner of the parent, you set the child’s position to (50, 50) on the canvas, OR you set it relative to the parent. var parentView = new Rectangle(300, 400); parentView
Wait, careful: In most Canvas-based libraries, add(child) adds to absolute coordinates. To simulate nesting, we manually offset.
var contentView = new Rectangle(260, 300); contentView.setColor("white"); contentView.setBorderWidth(1); contentView.setPosition(parentView.getX() + 20, parentView.getY() + 80); add(contentView); Place a button or a text block inside contentView .