This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to center a <div> on a page vertically and horizontally?
I have a canvas element, and I'd like it to be right in the very center of a page, both vertical and horizontal.
I'm a programmer, and I don't much about CSS. Can anybody help me with centering my canvas both vertically and horizontally?
Here's my current CSS code:
/* Set up canvas style */
#canvas {
font-family: 'pixel';
margin-left: auto;
margin-right: auto;
display: block;
border: 1px solid black;
cursor: none;
outline: none;
}
It's already being centered horizontally, but not vertically, thank you in advance!
this should do the trick:
#canvas {
position: absolute;
top: 50%; left: 50%;
width: 200px;
height: 200px;
margin: -100px 0 0 -100px;
}
The margin top and left has to be negative half the height and width of the element.
The same principal applies if you don't know the width and height and need to calculate it with javascript. Just get the width/height, divide those by half and set the values as a margin in the same way as the example above.
Hope that helps :)
I don't know if this would help, but I wrote this jQuery plugin that might help. I also know this script needs adjustments. It'd adjust the page when needed.
(function($){
$.fn.verticalCenter = function(){
var element = this;
$(element).ready(function(){
changeCss();
$(window).bind("resize", function(){
changeCss();
});
function changeCss(){
var elementHeight = element.height();
var windowHeight = $(window).height();
if(windowHeight > elementHeight)
{
$(element).css({
"position" : 'absolute',
"top" : (windowHeight/2 - elementHeight/2) + "px",
"left" : 0 + "px",
'width' : '100%'
});
}
};
});
};
})(jQuery);
$("#canvas").verticalCenter();
Refined Code + Demo
Please, view this demo in "Full page" mode.
(function($) {
$.fn.verticalCenter = function(watcher) {
var $el = this;
var $watcher = $(watcher);
$el.ready(function() {
_changeCss($el, $watcher);
$watcher.bind("resize", function() {
_changeCss($el, $watcher);
});
});
};
function _changeCss($self, $container) {
var w = $self.width();
var h = $self.height();
var dw = $container.width();
var dh = $container.height();
if (dh > h) {
$self.css({
position: 'absolute',
top: (dh / 2 - h / 2) + 'px',
left: (dw / 2 - w / 2) + 'px',
width: w
});
}
}
})(jQuery);
$("#canvas").verticalCenter(window);
$(function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
drawSmile(ctx, 0.9, 'yellow', 'black', 0.75);
});
function drawSmile(ctx, scale, color1, color2, smilePercent) {
var x = 0, y = 0;
var radius = canvas.width / 2 * scale;
var eyeRadius = radius * 0.12;
var eyeXOffset = radius * 0.4;
var eyeYOffset = radius * 0.33;
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.beginPath(); // Draw the face
ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = color1;
ctx.fill();
ctx.lineWidth = radius * 0.05;
ctx.strokeStyle = color2;
ctx.stroke();
ctx.beginPath(); // Draw the eyes
ctx.arc(x - eyeXOffset, y - eyeYOffset, eyeRadius, 0, 2 * Math.PI, false);
ctx.arc(x + eyeXOffset, y - eyeYOffset, eyeRadius, 0, 2 * Math.PI, false);
ctx.fillStyle = color2;
ctx.fill();
ctx.beginPath(); // Draw the mouth
ctx.arc(0, 0, radius * 0.67, Math.PI * (1 - smilePercent), Math.PI * smilePercent, false);
ctx.stroke();
ctx.restore();
}
#canvas {
border: 3px dashed #AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="canvas" width="256" height="256"></canvas>
Related
I am really stuck. My div contains fixed size divs, texts and images with a lot of pixel based positioning. How can I just wrap them in another div and make them scale to fit the wrapper?
This might be very similar: https://css-tricks.com/scaled-proportional-blocks-with-css-and-javascript/
Let's say that some elements have a class of .scaled-wrapper, and such elements have a single child named .scaled-content. Then we have a function applyScaling which takes a single .scaled-wrapper element, and scales its child accordingly:
let scaledWrapper = document.getElementsByClassName('scaled-wrapper')[0];
let applyScaling = scaledWrapper => {
// Get the scaled content, and reset its scaling for an instant
let scaledContent = scaledWrapper.getElementsByClassName('scaled-content')[0];
scaledContent.style.transform = 'scale(1, 1)';
let { width: cw, height: ch } = scaledContent.getBoundingClientRect();
let { width: ww, height: wh } = scaledWrapper.getBoundingClientRect();
let scaleAmtX = ww / cw;
let scaleAmtY = wh / ch;
scaledContent.style.transform = `scale(${scaleAmtX}, ${scaleAmtY})`;
};
applyScaling(scaledWrapper);
// ---- The rest of the code is just for the demonstration ui ----
let change = () => {
let w = parseInt(wInp.value);
let h = parseInt(hInp.value);
if (!isNaN(w)) scaledWrapper.style.width = `${w}px`;
if (!isNaN(h)) scaledWrapper.style.height = `${h}px`;
scaledWrapper.getElementsByClassName('scaled-content')[0].innerHTML = textInp.value;
applyScaling(scaledWrapper);
};
let wInp = document.createElement('input');
wInp.setAttribute('placeholder', 'input parent width in px');
wInp.addEventListener('input', change);
wInp.value = '200';
document.body.appendChild(wInp);
let hInp = document.createElement('input');
hInp.setAttribute('placeholder', 'input parent height in px');
hInp.addEventListener('input', change);
hInp.value = '200';
document.body.appendChild(hInp);
let textInp = document.createElement('input');
textInp.setAttribute('placeholder', 'input text content');
textInp.addEventListener('input', change);
textInp.value = 'abc';
document.body.appendChild(textInp);
.scaled-wrapper {
position: absolute;
left: 10px; top: 30px;
width: 200px; height: 200px;
outline: 1px solid red;
z-index: 1;
}
.scaled-content {
box-sizing: border-box;
display: inline-block;
transform-origin: 0 0;
background-color: #ffd0d0;
z-index: -1;
}
<div class="scaled-wrapper"><div class="scaled-content">abc</div></div>
The main idea is to take the ratio of the size between parent/child, and use that to scale the child accordingly. Note that it's important that the child's transform-origin is the top-left corner (having transform-origin: 50% 50% causes the child to be centered around the parent's top-left corner).
Also note that applyScaling needs to be called if the size of the parent ever changes (for example, if the parent is a percentage size of the window, and the window resizes).
Using #Gershom's snippet, but keeping aspect ratio
let scaledWrapper = document.getElementsByClassName('scaled-wrapper')[0];
let applyScaling = scaledWrapper => {
// Get the scaled content, and reset its scaling for an instant
let scaledContent = scaledWrapper.getElementsByClassName('scaled-content')[0];
scaledContent.style.transform = 'scale(1, 1)';
let { width: cw, height: ch } = scaledContent.getBoundingClientRect();
let { width: ww, height: wh } = scaledWrapper.getBoundingClientRect();
// let scaleAmtX = ww / cw;
// let scaleAmtY = wh / ch;
let scaleAmtX = Math.min(ww / cw, wh / ch);
let scaleAmtY = scaleAmtX;
scaledContent.style.transform = `scale(${scaleAmtX}, ${scaleAmtY})`;
};
applyScaling(scaledWrapper);
// ---- The rest of the code is just for the demonstration ui ----
let change = () => {
let w = parseInt(wInp.value);
let h = parseInt(hInp.value);
if (!isNaN(w)) scaledWrapper.style.width = `${w}px`;
if (!isNaN(h)) scaledWrapper.style.height = `${h}px`;
scaledWrapper.getElementsByClassName('scaled-content')[0].innerHTML = textInp.value;
applyScaling(scaledWrapper);
};
let wInp = document.createElement('input');
wInp.setAttribute('placeholder', 'input parent width in px');
wInp.addEventListener('input', change);
wInp.value = '100';
document.body.appendChild(wInp);
let hInp = document.createElement('input');
hInp.setAttribute('placeholder', 'input parent height in px');
hInp.addEventListener('input', change);
hInp.value = '100';
document.body.appendChild(hInp);
let textInp = document.createElement('input');
textInp.setAttribute('placeholder', 'input text content');
textInp.addEventListener('input', change);
textInp.value = 'abc';
document.body.appendChild(textInp);
.wrapper-wrapper {
box-sizing: border-box;
border: solid 2px blue;
position: relative;
}
.scaled-wrapper {
position: relative;
width: 100px; height: 100px;
outline: 1px solid red;
z-index: 1;
}
.scaled-content {
box-sizing: border-box;
display: inline-block;
transform-origin: 0 0;
background-color: #ffd0d0;
z-index: -1;
}
<div class="wrapper-wrapper">
<div class="scaled-wrapper">
<div class="scaled-content">abc</div>
</div>
</div>
For React you can do it like this:
const applyScaling = (scaledWrapper, scaledContent) => {
scaledContent.style.transform = 'scale(1, 1)';
let { width: cw, height: ch } = scaledContent.getBoundingClientRect();
let { width: ww, height: wh } = scaledWrapper.getBoundingClientRect();
let scaleAmtX = Math.min(ww / cw, wh / ch);
let scaleAmtY = scaleAmtX;
scaledContent.style.transform = `scale(${scaleAmtX}, ${scaleAmtY})`;
};
const App = ()=>{
const scaledWrapper=useRef();
const scaledContent=useRef();
useEffect(()=>{
if (scaledWrapper.current && scaledContent.current) {
applyScaling(scaledWrapper.current, scaledContent.current);
}
},[scaledWrapper.current,scaledContent.current]);
return(
<div ref={scaledWrapper}>
<div ref={scaledContent}></div>
</div>
);
}
scale() is relative to the size of the current container.
height and width are relative to the size of the parent container.
In this case, I would simply set both height and width to 100% to fill the parent DOM element. If you must use scale - try 100%. After setting height and width.
Suppose I have the following HTML:
<div>
<canvas class="colorPicker" width="800" height="800"></canvas>
<canvas class="colorPicker" width="800" height="800"></canvas>
</div>
And, this CSS:
div {
display: flex;
width: 100%;
overflow: hidden;
}
div > canvas{
flex-grow: 1;
flex-shrink: 1;
width: 50%;
}
The canvases are not scaled proportionally. They are taller than they are wide. This is visible when I paint circles on the canvas.
(JSFiddle: https://jsfiddle.net/08rckfek/)
Why is this happening?
If I don't use flexbox in the parent div, the canvases are scaled correctly.
Furthermore, it seems weird that I have to specify width: 50% at all. flex-shrink is ignored, even if I specify a basis.
How can I make a row of canvases that automatically scale proportionally based on the width of the parent flexbox?
You need to set align-items as by default its value is stretch
document.addEventListener('DOMContentLoaded', (e) => {
document.querySelectorAll('canvas.colorPicker').forEach((canvas) => {
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = Math.min(canvas.width, canvas.height) / 2;
// Base white circle, so middle has a full color
ctx.beginPath();
ctx.arc(centerX, centerY, radius/2, 0, 2*Math.PI, false);
ctx.closePath();
ctx.fillStyle = '#fff';
ctx.fill();
for (let angle=0; angle<=360; angle+=1) {
const startAngle = (angle-2)*Math.PI/180;
const endAngle = angle * Math.PI/180;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.closePath();
const gradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
gradient.addColorStop(0, 'hsl(' + angle + ', 100%, 100%)');
gradient.addColorStop(0.5, 'hsl(' + angle + ', 100%, 50%)');
gradient.addColorStop(1, 'hsl(' + angle + ', 100%, 0%)');
ctx.fillStyle = gradient;
ctx.fill();
}
});
});
div {
display: flex;
width: 100%;
overflow: hidden;
align-items:flex-start;
}
div > canvas{
flex-grow: 1;
flex-shrink: 1;
width: 50%;
}
<div>
<canvas class="colorPicker" width="800" height="800"></canvas>
<canvas class="colorPicker" width="800" height="800"></canvas>
</div>
I am having trouble placing a div over a canvas where the canvas is still visible. I can only get it to where the div is over the canvas but the canvas is hidden. If anyone has an example that would be lovely.
var canvas = document.querySelector('canvas');
canvas.width = screen.width;
canvas.height = screen.height;
var context = canvas.getContext('2d');
var tau = 2 * Math.PI;
function Triangle(canvs, cnt, sid, f) {
this.phase = 0;
this.ctx = canvs.getContext('2d');
this.first = f;
this.sides = sid;
this.canv = canvs;
this.draw = drawTriangle;
this.size = 100;
}
function drawTriangle() {
requestAnimationFrame(drawTriangle.bind(this));
var x = 0;
var y = 0;
var centerX = this.canv.width / 2;
var centerY = this.canv.height / 4;
this.phase += 0.005 * tau;
if (this.first == 1) {
this.ctx.clearRect(0, 0, this.canv.width, this.canv.height);
}
this.ctx.beginPath();
for (var i = 0; i <= this.sides; i++) {
this.ctx[i ? 'lineTo' : 'moveTo'](
centerX + this.size * Math.cos(this.phase + i / this.sides * tau),
centerY + this.size * Math.sin(this.phase + i / this.sides * tau)
);
}
this.ctx.strokeStyle = '#dda36b';
this.ctx.stroke();
this.size--;
}
var collection = [];
var triangle1 = new Triangle(canvas, context, 3, 1);
triangle1.draw();
var i = 0;
function nextFrame() {
if (i < 1000) {
collection[i] = new Triangle(canvas, context, 3, 0);
collection[i].draw();
i++;
setTimeout(nextFrame, 500);
}
}
setTimeout(nextFrame, 0);
body {
background-color: #19191b
}
<div align="center">
<button id="test">Test button that needed some text to make it longer</button>
<br>
</div>
<div>
<canvas></canvas>
</div>
So the button takes up the entire width of the screen and you cannot see anything beneath it. I would like the div to be transparent so you can see the triangles beneath it.
Use position:absolute so you can freely position elements in their parent element with top or bottom and left or right. This allows HTML elements to overlap. Make sure that those elements you want to be in the foreground come after those you want to be in the background (or alternatively, use the z-index CSS property).
This is your code slightly modified for faster results. I did not change anything of matter in the JS section (just removed the resizing code so the demonstrated behavior is visible sooner). Interesting are the changes to the CSS and HTML below.
var canvas = document.querySelector('.mycanvas');
var context = canvas.getContext('2d');
var tau = 2 * Math.PI;
function Triangle(canvs, cnt, sid, f) {
this.phase = 0;
this.ctx = canvs.getContext('2d');
this.first = f;
this.sides = sid;
this.canv = canvs;
this.draw = drawTriangle;
this.size = 100;
}
function drawTriangle() {
requestAnimationFrame(drawTriangle.bind(this));
var x = 0;
var y = 0;
var centerX = this.canv.width / 2;
var centerY = this.canv.height / 4;
this.phase += 0.005 * tau;
if (this.first == 1) {
this.ctx.clearRect(0, 0, this.canv.width, this.canv.height);
}
this.ctx.beginPath();
for (var i = 0; i <= this.sides; i++) {
this.ctx[i ? 'lineTo' : 'moveTo'](
centerX + this.size * Math.cos(this.phase + i / this.sides * tau),
centerY + this.size * Math.sin(this.phase + i / this.sides * tau)
);
}
this.ctx.strokeStyle = '#dda36b';
this.ctx.stroke();
this.size--;
}
var collection = [];
var triangle1 = new Triangle(canvas, context, 3, 1);
triangle1.draw();
var i = 0;
function nextFrame() {
if (i < 1000) {
collection[i] = new Triangle(canvas, context, 3, 0);
collection[i].draw();
i++;
setTimeout(nextFrame, 500);
}
}
setTimeout(nextFrame, 0);
.mycanvas {
position:absolute;
background-color: #19191b
}
.mydiv {
position:absolute;
left:100px;
top:30px;
opacity:0.5;
background-color: rgb(100, 100, 200);
}
<div>
<div>
<canvas class="mycanvas"></canvas>
</div>
<div class="mydiv">
Hello World!
</div>
</div>
Three.js is an awesome library. Its well documented and its working great.
I am trying to render a plane along with trackball control inside a div. The div resizes as the window or the browser is resized. Following is the issue i am facing
When the browser finishes loading, the plane is displayed in the browser, However, it is not refreshing or responding to the trackball control. But when i minimize the browser or switch tabs the scene becomes active and it works as designed. I am sure the trackball and the scene is working upon load as i am able to see the changes when i refresh it by minimizing the browser or switching tabs. I believe it has to do with rendering or refreshing on load.
Similarly, when i resize the browser the div changes its size but the scene goes back to the frozen state. Once again, if i minimize or switch tabs the scene is resized and works as intended.
I am not able to figure out where the issue is.
Thanks a lot
Sam
<!DOCTYPE html>
<html
lang="en">
<head>
<title>three.js
canvas
-
geometry
-
cube
</title>
<meta
charset="utf-8">
<meta
name="viewport"
content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #f0f0f0;
margin: 0px;
overflow: hidden;
}
#Cont3D {
min-width: 200px;
min-height: 400px;
float: none;
margin-left: 20%;
margin-right: 20%;
border-width: thick;
border-style: solid;
margin-top: 100px;
}
</style>
</head>
<body>
<script
src="build/three.js"></script>
<script
src="js/loaders/STLLoader.js"></script>
<script
src="js/renderers/SoftwareRenderer.js"></script>
<script
src="js/controls/TrackballControls_Persp.js"></script>
<script
src="js/modifiers/SubdivisionModifier.js"></script>
<script
src="js/controls/OrbitControls.js"></script>
<script
src="js/libs/stats.min.js"></script>
<script
src="js/Detector.js"></script>
<script>
function startmusic() {
var container, stats;
var camera, scene, renderer;
var plane;
var targetRotationX = 0;
var targetRotationOnMouseDownX = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
var targetRotationY = 0;
var targetRotationOnMouseDownY = 0;
var mouseY = 0;
var mouseYOnMouseDown = 0;
var Width, Height;
init();
animate();
function init() {
container = document.getElementById("Cont3D");
var info = document.createElement('div');
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'Drag to spin the cube';
container.appendChild(info);
Width = container.clientWidth;
Height = container.clientHeight;
camera = new THREE.PerspectiveCamera(50, Width / Height, 1, 2000);
camera.position.y = 150;
camera.position.z = 500;
scene = new THREE.Scene();
// Plane
var geometry = new THREE.PlaneGeometry(200, 200);
geometry.applyMatrix(new THREE.Matrix4().makeRotationX(-Math.PI / 2));
var material = new THREE.MeshBasicMaterial({
color: 0xe0e0e0
});
plane = new THREE.Mesh(geometry, material);
scene.add(plane);
//LIGHTS
hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
hemiLight.color.setHSL(0.6, 1, 0.6);
hemiLight.groundColor.setHSL(0.095, 1, 0.75);
hemiLight.position.set(0, 500, 0);
scene.add(hemiLight);
scene.fog = new THREE.Fog(0xffffff, 3000, 10000);
scene.fog.color.setHSL(0.6, 0.87, 0.96);
spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(0, 1800, 0);
spotLight.target.position.set(0, 0, 0);
spotLight.castShadow = true;
scene.add(spotLight);
// RENDERER
// directional lighting
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position = camera.position; // .set(1, 1, 1).normalize();
scene.add(directionalLight);
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setClearColor(scene.fog.color, 1);
document.getElementById("logBox").innerHTML = container.style.width + "," + Width;
renderer.setSize(Width, Height);
container.appendChild(renderer.domElement);
controls = new THREE.TrackballControls(camera, renderer.domElement)
controls.rotateSpeed = .8;
controls.zoomSpeed = .7;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = false;
controls.dynamicDampingFactor = 0.6;
controls.maxDistance = 1000;
controls.minDistance = 150;
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild(stats.domElement);
controls.addEventListener('change', render);
container.addEventListener('resize', onWindowResize, false);
}
function onWindowResize(event) {
Width = container.clientWidth;
Height = container.clientHeight;
document.getElementById("logBox").innerHTML = Width + "," + Height;
camera.aspect = Width / Height;
camera.updateProjectionMatrix();
renderer.setSize(Width, Height);
controls.handleResize();
renderer.render(scene, camera);
}
function animate() {
requestAnimationFrame(animate);
render();
controls.update();
stats.update();
}
function render() {
renderer.render(scene, camera);
}
window.onresize = onWindowResize;
}
window.onload = startmusic;
</script>
<div
id="logBox"
style="position: absolute; top: 50px; width: 100%; text-align: center;">Blue</div>
<div
id="Cont3D">
</div>
</body>
</html>
function onWindowResize(event) {
Width = container.clientWidth;
Height = container.clientHeight;
document.getElementById("logBox").innerHTML = Width + "," + Height;
renderer.setSize(width, height);
camera.aspect = Width / Height;
camera.updateProjectionMatrix();
controls.handleResize();
}
You don't need
renderer.render(scene, camera);
In your resize handler.
I'm trying to replicate something similar to the following map, where the polygonal area is transparent and the surrounding area is semi-transparent:
Can anyone help with this?
Here's the original:
https://energyeasy.ue.com.au/outages/powerOutages
Using some CSS and a large 512 x 512px png I have managed to emulate what I wanted to achieve.
I'm sure there would be more accurate methods but this has worked for me.
http://www.syn-rg.com.au/Development/United-Energy/mg_map/MG_Area_map_02.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0; }
#map_canvas {
background-color: #EAEAEA;
border: 1px solid #CCCCCC;
height: 400px;
margin-bottom: 10px;
margin-left: auto;
margin-right: auto;
width: 532px;
}
#map_canvas div div div div div img{ border:1000px solid black;margin:-1000px -1000px;}
/*#map_canvas div div div div div div div{ background: none repeat scroll 0px 0px rgba(0, 0, 0, 0.5);}*/
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA7UaoyrY4KyoW1iEU0KFo0ZOxH5w30oZ8&sensor=true"></script>
<script type="text/javascript">
var overlay;
USGSOverlay.prototype = new google.maps.OverlayView();
function initialize() {
var myLatLng = new google.maps.LatLng(-37.815676, 145.449005);
var myOptions = {
zoom: 9,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var swBound = new google.maps.LatLng(-38.269876, 144.842405); // Latitude, Longitude = 182.749 or 107.183 or 108.4443 or 107.77615
var neBound = new google.maps.LatLng(-37.161476, 146.249005); // -0.5542, +0.7033 = 256px
//var swBound = new google.maps.LatLng(-37.783, 144.966);
//var neBound = new google.maps.LatLng(-37.225, 145.66930);
//var swBound = new google.maps.LatLng(62.281819, -150.287132);
//var neBound = new google.maps.LatLng(62.400471, -150.005608);
var bounds = new google.maps.LatLngBounds(swBound, neBound);
// Photograph courtesy of the U.S. Geological Survey
var srcImage = 'images/mg_map_full.png';
overlay = new USGSOverlay(bounds, srcImage, map);
}
function USGSOverlay(bounds, image, map) {
// Now initialize all properties.
this.bounds_ = bounds;
this.image_ = image;
this.map_ = map;
// We define a property to hold the image's div. We'll
// actually create this div upon receipt of the onAdd()
// method so we'll leave it null for now.
this.div_ = null;
// Explicitly call setMap on this overlay
this.setMap(map);
}
USGSOverlay.prototype.onAdd = function () {
// Note: an overlay's receipt of onAdd() indicates that
// the map's panes are now available for attaching
// the overlay to the map via the DOM.
// Create the DIV and set some basic attributes.
var div = document.createElement('div');
div.style.borderStyle = "none";
div.style.borderWidth = "0";
div.style.borderColor = "red";
div.style.position = "absolute";
div.style.opacity = "0.3";
// Create an IMG element and attach it to the DIV.
var img = document.createElement("img");
img.src = this.image_;
img.style.width = "100%";
img.style.height = "100%";
img.style.position = 'absolute';
div.appendChild(img);
// Set the overlay's div_ property to this DIV
this.div_ = div;
// We add an overlay to a map via one of the map's panes.
// We'll add this overlay to the overlayImage pane.
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
}
USGSOverlay.prototype.draw = function () {
// Size and position the overlay. We use a southwest and northeast
// position of the overlay to peg it to the correct position and size.
// We need to retrieve the projection from this overlay to do this.
var overlayProjection = this.getProjection();
// Retrieve the southwest and northeast coordinates of this overlay
// in latlngs and convert them to pixels coordinates.
// We'll use these coordinates to resize the DIV.
var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
// Resize the image's DIV to fit the indicated dimensions.
var div = this.div_;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
div.style.height = (sw.y - ne.y) + 'px';
}
USGSOverlay.prototype.onRemove = function () {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="position: relative; background-color: rgb(229, 227, 223); overflow: hidden;"></div>
</body>
</html>