I've been using this code:
<div class="divClassName">
<button onClick="functionName1();");'>Enter Text Here</button>
<script>
function functionName1() {
var src = "name.jpg";
show_image("name.jpg", 200, 200, "absolute", 1, "<alt>");
}
function show_image(src, width, height, position, zIndex, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height
img.position = position;
img.style.zIndex = zIndex;
img.alt = alt;
document.body.appendChild(img);
}
</script>
</div>
<!-- Use actual names for divClassName, functionName1, and name.jpg if you want to. -->
This makes images appear upon button click, but it appears in the top left corner of the screen instead of where I want it to be. I've been trying
function show_image(src, width, height, position, left, top, zIndex, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height
img.position = position;
img.left = left;
img.top = top;
img.style.zIndex = zIndex;
img.alt = alt;
...But it doesn't work. Any fixes/answers?
EDIT: Question answered. Used:
img.style.position = position;
img.style.left = left;
img.style.top = top;
Updated :
If you assign position:absolute ,then you must have to give their left , top or bottom , right !
So :
you have to pass extra parameter to your function, where you want to show your img:
function show_image(src, width, height, position,left,top, zIndex, alt) { //left,top as example
var img = document.createElement("img");
img.src = src;
img.style.width = width;
img.style.height = height
img.style.position = position;
img.style.left = left+'px';
img.style.top = top+'px';
img.style.zIndex = zIndex;
img.alt = alt;
document.body.appendChild(img);
}
Or Another Short way to give Style to img is :
img.attributes = "style = left:"+left+"px;top:"+top+"px;...And So on..";
You are positioning the image absolute. So if top = 0 and left = 0 it will render in the top left of the screen.
If you want it to render in the top left of the div. You can still position your image absolute with top = 0 and left = 0.
But: you need to give the parent element a position relative.
so for example:
<body>
<div id="container">
// img src etc...
</div>
<body>
and the css should be
#container {
width: 960px;
height: 500px;
margin: 100px auto;
position: relative;
}
img {
position: absolute;
top: 0;
left: 0;
}
Related
We need to implement a screen saver which should have 3 images.
The bottom image should be fixed.
Middle image will be moving.
Top image will be moving at relatively higher speed.
We created 3 divs to handle the images as below.
<!DOCTYPE html>
<html>
<head>
<title>Moving Screen Saver</title>
<style>
html, body {
position: relative;
height: 100%;
width: 100%;
}
#bgimg {
background-image: url("background/moon_bg.png");
position: absolute;
background-repeat: no-repeat;
background-size: cover;
width: 100%;
height: 100%;
}
.animator {
width: 100vw;
height: 100vh;
}
#poster {
background-image: url("posters/gladiator.png");
position: absolute;
background-position:right 20px bottom 20px;
background-repeat: no-repeat;
width: 100%;
height: 100%;
background-color: transparent;
}
</style>
</head>
<body>
<div id="bgimg"></div>
<div class="animator"></div>
<div id="poster"></div>
<script>
var poster = document.getElementById('poster');
var animate;
function moveRight()
{
poster.style.left = poster.style.left || 0;
poster.style.left = parseInt(poster.style.left) - 10 + 'px';
requestAnimationFrame(moveRight);
}
moveRight();
function rollAnimate(element, url) {
if(!element instanceof HTMLElement)
return;
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
var x = 0;
var pattern;
var framesPerSec = 10;
img.onload = startDrawing;
img.onerror = console.error;
img.src = url;
canvas.style.cssText = 'position:absolute;'
function startDrawing() {
element.insertBefore(canvas, element.firstChild);
pattern = ctx.createPattern(img, 'repeat');
resize();
anim();
window.addEventListener('resize', resize, {passive: true});
}
function anim() {
x = (x - 1) % img.width;
ctx.setTransform(1,0,0,1,x,(canvas.height) - (img.height));
ctx.fill();
setTimeout(function() {
requestAnimationFrame(anim);
}, 1000 / framesPerSec);
}
function resize(evt) {
canvas.width = element.offsetWidth;
canvas.height = element.offsetHeight;
ctx.fillStyle = pattern;
ctx.rect(0, canvas.height - img.height, canvas.width, img.height);
ctx.globalCompositeOperation = 'copy';
}
}
rollAnimate(document.querySelector('.animator'), 'buildings/mod_cropped.png');
</script>
</body>
</html>
lower image - bgimg
middle image - animator
top image - poster
We are able to see lower image which is fixed and middle image which is moving. But poster image is not visible. We are thinking that this is because when we are trying to paint middle image it is replacing top image. Can any one please help me to fix this issue.
Below is jsfiddle page
https://jsfiddle.net/n76epste/10/
So when I look, you are actually getting all 3 images. Your issue is the poster moves off screen super fast and never returns.
bgimg is static and covered by animator (you can see this by deleting animator)
animator is animated and repeating and cover bgimage
poster is given an ever updating style="left: -***px" where * is an increasing number. (You can see this for a split second when loading the page if you hide bgimg and animator with css)
This is because of Z-index. I changed z-index of poster dev tp the highest to fix the problem.
I'm trying to use the image generated by https://github.com/qrohlf/trianglify as a background image as the author does on his website (http://qrohlf.com/trianglify/). How do I overlay a div on the document.body.appendChild.
The Trianglify library provides a .png() method we can use to add a dynamically generated image to the page.
This first method simply sets the document.body.style.backgroundImage to the generated Trianglify image. In both cases we'll use window.innerHeight and window.innerWidth to get the height and width of the window when creating the Trianglify image.
// Create the Trianglify image
var pattern = Trianglify({
height: window.innerHeight,
width: window.innerWidth,
cell_size: 30});
document.body.style.backgroundSize = "cover";
document.body.style.backgroundImage = "url(" + pattern.png() + ")";
html,
body {
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/trianglify/1.0.1/trianglify.min.js"></script>
Here's our HTML body.
You could also create an element, and set the Trianglify image as the background on it, to overlay it on the page.
// Create the Trianglify image
var pattern = Trianglify({
height: window.innerHeight,
width: window.innerWidth,
cell_size: 30});
var overlay = document.createElement("div");
overlay.style.position = "absolute";
overlay.style.top = "0";
overlay.style.left = "0";
overlay.style.height = "100%";
overlay.style.width = "100%";
overlay.style.opacity = "0.8";
overlay.style.backgroundSize = "cover";
overlay.style.backgroundImage = "url(" + pattern.png() + ")";
document.body.appendChild(overlay);
html,
body {
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/trianglify/1.0.1/trianglify.min.js"></script>
Here's our HTML body.
We currently upload an image via the below code:
reader.onload = function (event) {
fabric.Image.fromURL(event.target.result, function (img) {
whiteboardService.uploadImageToCanvas(img);
});
}
and...
service.uploadImageToCanvas = function (image) {
service.canvas.add(image);
image.id = service.getUniqueId();
service.objectMap[image.id] = image;
var data = {
image: image,
id: image.id
};
signalService.sendMessage(service.recipient, data);
};
If the image is too large, bigger than our fixed width and height of the canvas would it be possible for that image to be scaled down automatically to fit into the fixed width and height of the canvas?
I should point out that I am using Angular.js as well
ta
fabricjs put a very simple method to do this.
Those methods are scaleToWidth and scaleToHeight that are close to 'apply a scale factor that will fit the image on the specified dimensions'
So you can do
image.scaleToWidth(service.canvas.getWidth());
service.canvas.add(image);
it depends if you want to preserve aspect ratio if you have to scale for the biggest, the smallest or both.
Inspired by #AndreaBogazzi, I wrote below code to fit image to canvas totally.
var canvas = new fabric.Canvas('canvas');
fabric.Image.fromURL('https://d32ogoqmya1dw8.cloudfront.net/images/NAGTWorkshops/structure/SGT2012/activities/noaa_global_topographic_map.jpg', function(oImg) {
let imgWidth = oImg.width;
let imgHeight = oImg.height;
let canvasWidth = canvas.getWidth();
let canvasHeight = canvas.getHeight();
let imgRatio = imgWidth / imgHeight;
let canvasRatio = canvasWidth / canvasHeight;
if(imgRatio <= canvasRatio){
if(imgHeight> canvasHeight){
oImg.scaleToHeight(canvasHeight);
}
}else{
if(imgWidth> canvasWidth){
oImg.scaleToWidth(canvasWidth);
}
}
canvas.clear();
canvas.add(oImg);
canvas.centerObject(oImg);
});
.image-preview{
border: solid 1px #979797;
width: 200px;
height: 200px;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.1/fabric.min.js"></script>
<div class="image-preview">
<canvas id="canvas" width='200' height='200'></canvas>
<hr/>
<p>Origin Image</p>
<img src="https://d32ogoqmya1dw8.cloudfront.net/images/NAGTWorkshops/structure/SGT2012/activities/noaa_global_topographic_map.jpg" />
</div>
I need to get the color of any pixel my mousepointer is currently hovering.
I found several solutions for canvas elements, but none for a background image defined in CSS for a element.
How can I achieve this?
Combining the answers from Get a CSS value with JavaScript and How to get a pixel's x,y coordinate color from an image?, I was able to simulate what you are looking for: JSFiddle
<html>
<head>
<style type="text/css">
#test {
background-image: url('http://jsfiddle.net/img/logo.png');
background-color: blue;
background-repeat: no-repeat;
height: 30px;
width: 100%;
}
#hidden {
display: none;
}
</style>
<script type="text/javascript">
var div = document.getElementById("test");
var style = window.getComputedStyle(div);
div.onmousemove = function(e) {
var path = style.getPropertyValue('background-image');
path = path.substring(4, path.length-1);
var img = document.getElementById("i1");
img.src = path;
var canvas = document.getElementById("c1");
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;
var values = document.getElementById("values");
values.innerHTML = 'R: ' + pixelData[0] + '<br>G: ' + pixelData[1] + '<br>B: ' + pixelData[2] + '<br>A: ' + pixelData[3];
};
</script>
</head>
<body>
<div id="test"></div>
<div id="hidden">
<img id="i1" src="" />
<canvas id="c1"></canvas>
</div>
<div id="values"></div>
</body>
</html>
I retrieved the computed style (var style = window.getComputedStyle(div);) outside of the mouse move function for performance reasons, but if the background image is going to change dynamically, then it may need to be moved into the function.
There are some possible browser constraints for using getComputedStyle.
SCALING
You could try editing the code to adjust for the scale:
var h = parseInt(style.getPropertyValue("width")),
w = parseInt(style.getPropertyValue("height"));
var img = document.getElementById("i1");
img.src = path;
var canvas = document.getElementById("c1");
canvas.width = h;
canvas.height = w;
canvas.getContext('2d').drawImage(img, 0, 0, w, h);
This also includes a change to the CSS: JSFiddle
This is the layout and design of my page.
HTML Code:
<div id="myid_browse_modal_image" >
<image id="img_browse" src=""></image>
</div>
<div id="div_myphoto">
<img id="img_myphoto" src="" alt="ID Photo"/>
</div>
CSS Code:
#myid_browse_modal_image
{
height: 370px;
line-height: 370px;
text-align:center;
border: 1px;
border-style: solid;
border-color: gray;
}
#myid_browse_modal_image > img
{
max-width: 100%;
height: 100%;
}
#div_myphoto > img
{
width: 150px;
height: 150px;
max-width:150px;
max-height: 150px;
border: 2px;
border-style: solid;
border-color: black;
}
My problem goes like this. I am implementing a functionality where I can browse an image and be able to crop it. It looks like the image below:
When I click the "Set as an ID Photo", it calls function that do the cropping functionality:
function myid_browse_crop()
{
var img_browse = document.getElementById('img_browse');
var $img_browse = $(img_browse);
var img_myphoto= document.getElementById('img_myphoto');
var $img_myphoto = $(img_myphoto);
//Create a temporary canvas
var canvas= document.createElement("canvas");
canvas.id = "temp_canvas";
canvas.width = img_browse.width;
canvas.height = img_browse.height;
// get the canvas context;
var ctx = canvas.getContext('2d');
ctx.drawImage(img_browse, 0, 0);
//Get the position of my resizable div relative to the image
var relativeX = $(".browse-selection").offset().left - $("#img_browse").offset().left;
var relativeY = $(".browse-selection").offset().top - $("#img_browse").offset().top;
var relativeW = $(".browse-selection").width();
var relativeH = $(".browse-selection").height();
var imageData = ctx.getImageData(relativeX,relativeY, relativeW, relativeH);
// create destination canvas
var canvas1 = document.createElement("canvas");
canvas1.width = relativeW;
canvas1.height = relativeH;
var ctx1 = canvas1.getContext("2d");
ctx1.rect(0, 0, relativeW, relativeH);
ctx1.putImageData(imageData, 0, 0);
img_myphoto.src = canvas1.toDataURL();
}
The result cropped image is below, which is not right.
It might be because of the dimensions of the image. The image is smaller in reality(202 x 250 pixels), but it gets distorted when browse and selected because of the css below, making it (299 x 370 pixels):
#myid_browse_modal_image > img
{
max-width: 100%;
height: 100%;
}
How will I fix it? To get just the correct selected region. Anyways ".browse -selection" is a div with a dashed lines in the Image 1. It is generated by a jquery plug-in that's why it is not included in my Original HTML Code.
Change
#myid_browse_modal_image > img
{
max-width: 100%;
height: 100%;
}
To this:
#myid_browse_modal_image > img
{
max-width: 100%;
height: auto;
max-height: 370px !important;
}
This issue is cause by having an image file dimensions on disk, different from what is being rendered in the browser.
In this case,I edited my code:
function myid_browse_crop()
{
var img_browse = document.getElementById('img_browse');
var $img_browse = $(img_browse);
var img_myphoto= document.getElementById('img_myphoto');
var $img_myphoto = $(img_myphoto);
//Create a temporary canvas
var canvas= document.createElement("canvas");
canvas.id = "temp_canvas";
canvas.width = img_browse_width ;
canvas.height = img_browse_height;
// get the canvas context;
var ctx = canvas.getContext('2d');
ctx.drawImage(img_browse, 0, 0);
//Get the position of my resizable div relative to the image
var relativeX = $(".browse-selection").offset().left - $("#img_browse").offset().left;
var relativeY = $(".browse-selection").offset().top - $("#img_browse").offset().top;
var relativeW = $(".browse-selection").width();
var relativeH = $(".browse-selection").height();
var xrelativeX = relativeX * (img_browse_width /img_browse.width);
var xrelativeY = relativeY * (img_browse_height/img_browse.height);
var xrelativeW = (img_browse_width /img_browse.width)*relativeW;
var xrelativeH = (img_browse_height/img_browse.height)*relativeH;
var imageData = ctx.getImageData(xrelativeX,xrelativeY, xrelativeW,xrelativeH );
// create destination canvas
var canvas1 = document.createElement("canvas");
canvas1.width = xrelativeW ;
canvas1.height = xrelativeH;
var ctx1 = canvas1.getContext("2d");
ctx1.rect(0, 0, xrelativeW, xrelativeH);
ctx1.putImageData(imageData, 0, 0);
img_myphoto.src = canvas1.toDataURL();
}
img_browse_height and img_browse_width are the actual file size of the image on disk. I had acquired this variables from reading an image file through an input file:
function readURL(input, imageframe) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var image = new Image();
reader.onload = function (e) {
image.src = e.target.result;
image.onload = function() {
//Actual File Size in Disk of "#img_browse"
img_browse_width = this.width;
img_browse_height = this.height;
}
$('#img_browse')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}