How to save associated code with screenshots - javascript

I have to create a data set for a project I am doing. The task seems simple, I have to a create hundreds of screen shots of a GUI with one button taking a random position every time the code is run and save the image along with its CSS code. The css code should have the position of the button.
I can take the screen shot and save it with the button appearing on random location on the screen, but I am at a fail to save the CSS with location on the GUI.
I am using math random function to change the button location. Here is some code snippet.
<style>
#container
{
width:400px;
height:400px;
background-color:red;
}
#btn
{
position: absolute;
color: black;
width: 120px;
height: 30px;
}
</style>
<div id="container">
<button id="btn">Click Me!</button>
</div>
Javascript code to pass random number to button position:
<script>
var btn = document.getElementById("btn");
btn.style.top = Math.floor((Math.random() * 200) + 1) + "px";
btn.style.left = Math.floor((Math.random() * 200) + 1) + "px";
</script>
Saving a screenshot:
<script type="text/javascript">
//window.onload = function () {
var takeScreenShot = function () {
html2canvas(document.getElementById("container"), {
onrendered: function (canvas) {
var tempcanvas = document.getElementById("myCanvas");
var context = tempcanvas.getContext('2d');
context.drawImage(canvas, 0, 0, 400, 400, 0, 0, 400, 400);
var png = ReImg.fromCanvas(document.getElementById('myCanvas')).toPng();
var link = document.createElement("a");
link.href = tempcanvas.toDataURL('image/png');
link.download = 'screenshot.png';
link.click();
}
});
}
var myVar = setInterval(takeScreenShot, 5000);
</script>

Related

Why getComputedStyle() is not getting actual width and height is there any callback or event exists

I'm in such a situation where i need to wait till the image gets loaded once the image gets loaded i need to gets its computed height so that i can set the yellow color selector accordingly.
Question: based on computed height of image i'm setting yellow color selector. it works with setTimeout() randomly but i don't want such approach.
let images = ['https://via.placeholder.com/150','https://via.placeholder.com/110/0000FF/808080%20?Text=Digital.com','https://via.placeholder.com/80/0000FF/808080%20?Text=Digital.com'];
let image = `<img src="${images[Math.floor(Math.random()*images.length)]}"/>`
document.getElementById('content').innerHTML = `<div class="box">${image}</div>`;
//actual code
let height = window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height');
let imageWidth = window.getComputedStyle(document.querySelector('.box img'), null).getPropertyValue('width');
console.log('height',height,'width',imageWidth);
wrapImage = `<div style="width:calc(${imageWidth} + 10px);height:calc(${height} + 10px);position:absolute;left:0;top:0;border:1px solid yellow;"></div>`;
document.querySelector('.box').insertAdjacentHTML('beforeend',wrapImage);
.box{
width:100%;
height:auto;
border:1px solid red;
position:relative;
}
<div id="content">
</div>
with setTimeout it works but i don't want such approach,i want callback or some event once element is ready
let images = ['https://via.placeholder.com/150','https://via.placeholder.com/110/0000FF/808080%20?Text=Digital.com','https://via.placeholder.com/80/0000FF/808080%20?Text=Digital.com'];
let image = `<img src="${images[Math.floor(Math.random()*images.length)]}"/>`
document.getElementById('content').innerHTML = `<div class="box">${image}</div>`;
//actual code
setTimeout(() => {
let height = window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height');
let imageWidth = window.getComputedStyle(document.querySelector('.box img'), null).getPropertyValue('width');
console.log('height',height,'width',imageWidth);
wrapImage = `<div class="select" style="width:calc(${imageWidth} + 10px);height:${height};position:absolute;left:0;top:0;border:1px solid yellow;"></div>`;
document.querySelector('.box').insertAdjacentHTML('beforeend',wrapImage);
document.querySelector('.select').height = document.querySelector('.select').height + 10;
console.log('after computed height and added 10px',window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height'));
},700);
.box{
width:100%;
height:auto;
border:1px solid red;
position:relative;
}
<div id="content">
</div>
Please help me thanks in advance !!!
The image hasn't finished loading when you retrieved the height and width. To solve this, you'll need to wait for the images to load first, then get their height and width.
Listen for the window load event, which will fire when all resources (including images) have loaded completely:
let images = ['https://via.placeholder.com/150', 'https://via.placeholder.com/110/0000FF/808080%20?Text=Digital.com', 'https://via.placeholder.com/80/0000FF/808080%20?Text=Digital.com'];
let image = `<img src="${images[Math.floor(Math.random()*images.length)]}"/>`
document.getElementById('content').innerHTML = `<div class="box">${image}</div>`;
//actual code
window.addEventListener('load', function() {
let height = window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height');
let imageWidth = window.getComputedStyle(document.querySelector('.box img'), null).getPropertyValue('width');
console.log('height', height, 'width', imageWidth);
wrapImage = `<div class="select" style="width:calc(${imageWidth} + 10px);height:${height};position:absolute;left:0;top:0;border:1px solid yellow;"></div>`;
document.querySelector('.box').insertAdjacentHTML('beforeend', wrapImage);
document.querySelector('.select').height = document.querySelector('.select').height + 10;
console.log('after computed height and added 10px', window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height'));
});
.box {
width: 100%;
height: auto;
border: 1px solid red;
position: relative;
}
<div id="content">
</div>
To indicate selection you can use CSS outline property. That way you won't have to manage selection dimensions yourself.
Following is demo code. As you want to do it over multiple images, I've added 3 images. And you can select multiple images.
function changeImages() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].src = "https://via.placeholder.com/" + Math.floor(Math.random() * 50 + 50).toString() + "/0a0a0a/ffffff";
}
}
function setClickEvents() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].addEventListener("click", function(event) {
event.target.classList.toggle("selected");
});;
}
}
function init() {
document.getElementById('content').innerHTML = `<div id="box"></div>`;
var box = document.getElementById('box');
var img = document.createElement("img");
img.classList.add("selected");
box.appendChild(img);
box.appendChild(document.createElement("img"));
box.appendChild(document.createElement("img"));
setClickEvents();
changeImages();
}
#content {
padding: 15px;
margin: 10px;
}
#box {
width: 100%;
height: 120px;
border: 1px dotted red;
position: relative;
}
img {
margin: 15px;
}
/* use this class for marking selected elements */
.selected {
outline: thick double #f7d205;
outline-offset: 7px;
}
<!DOCTYPE html>
<html lang="en">
<body onload="init()">
<button onclick="changeImages()">Change Images</button>
<div id="content"></div>
</body>
</html>
Click on image to toggle selection.
If you want more flexibility then you can use Resize Observer. With this when you change src attribute of image tag you'll able to change selection size.
const imageObserver = new ResizeObserver(function(entries) {
for (let entry of entries) {
var img = entry.target;
let height = img.height + 10;
let width = img.width + 10;
console.log('Added 10px. height:', height, ' width:', width);
wrapImage = `<div class="select" style="width:${width}px;height:${height}px;position:absolute;left:0;top:0;border:1px solid #f7d205;"></div>`;
document.querySelector('.box').insertAdjacentHTML('beforeend', wrapImage);
}
});
function init() {
document.getElementById('content').innerHTML = `<div id="box" class="box"></div>`;
var box = document.getElementById('box');
var img = document.createElement("img");
img.src = "https://via.placeholder.com/" + Math.floor(Math.random() * 50 + 80).toString() + "/0a0a0a/ffffff";
box.appendChild(img);
imageObserver.observe(img);
}
<!DOCTYPE html>
<html lang="en">
<style>
#box {
width: 100%;
border: 1px dotted red;
position: relative;
}
</style>
<body onload="init()">
<div id="content"></div>
</body>
</html>
Note: Using same ResizeObserver you can observe multiple images:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
imageObserver.observe(images[i]);
}
Edit: As requested, demonstrating observing img resize from parent div element. Here the image is wrapped in div #box. On resize img dispatches a custom event and parent handles it.
function handleChildResize(event) {
console.log('parent: got it! handling it.. ')
var img = event.data;
let height = img.offsetHeight + 10;
let width = img.offsetWidth + 10;
console.log('Added 10px. height:', height, ' width:', width);
wrapImage = `<div class="select" style="width:${width}px;height:${height}px;position:absolute;left:0;top:0;border:2px solid #f7d205;"></div>`;
if (document.querySelector('.box > .select')) {
document.querySelector('.box > .select').remove();
}
document.querySelector('.box').insertAdjacentHTML('beforeend', wrapImage);
event.stopPropagation();
}
const imgObserver = new ResizeObserver(function(entries) {
for (let entry of entries) {
var img = entry.target;
var event = new Event('childResized');
event.data = img;
console.log("img: i am resized. Raising an event.");
img.dispatchEvent(event);
}
});
function init() {
var box = document.getElementById('box');
box.addEventListener('load', (event) => {
console.log('The page has fully loaded');
});
var img = document.createElement("img");
img.src = "https://via.placeholder.com/" + Math.floor(Math.random() * 50 + 80).toString() + "/0a0a0a/ffffff";
box.appendChild(img);
imgObserver.observe(img);
box.addEventListener('childResized', handleChildResize, true);
}
<!DOCTYPE html>
<html>
<head>
<style>
#box {
width: 100%;
padding: 10px;
border: 1px solid red;
position: relative;
}
</style>
</head>
<body onload="init()">
<div id="content">
<div id="box" class="box"></div>
</div>
</body>
</html>
You could consider adding the 'load' event listener as a callback for image loading.
Please check the example:
const image = document.getElementById('image');
const handler = () => {
alert(image.height);
};
image.addEventListener('load', handler);
<img src="https://image.shutterstock.com/z/stock-vector-sample-stamp-grunge-texture-vector-illustration-1389188336.jpg" id="image" />
I see that you want to compute the final value of the get computed style
you see. The thing is that the getComputedStyle doesn't get updated.
So just make a function to do it!
let images = ['https://via.placeholder.com/150','https://via.placeholder.com/110/0000FF/808080%20?Text=Digital.com','https://via.placeholder.com/80/0000FF/808080%20?Text=Digital.com'];'
let image = `<img src="${images[Math.floor(Math.random()*images.length)]}"/>`
document.getElementById('content').innerHTML = `<div class="box">${image}</div>`;
//actual code
setTimeout(() => {
let height;
let imageWidth;
function calculateHeightAndWidth() {
height = window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height');
imageWidth = window.getComputedStyle(document.querySelector('.box img'), null).getPropertyValue('width');
}
calculateHeightAndWidth()
console.log('height',height,'width',imageWidth);
wrapImage = `<div class="select" style="width:calc(${imageWidth} + 10px);height:${height};position:absolute;left:0;top:0;border:1px solid yellow;"></div>`;
document.querySelector('.box').insertAdjacentHTML('beforeend',wrapImage);
document.querySelector('.select').height = document.querySelector('.select').height + 10;
calculateHeightAndWidth()
console.log('after computed height and added 10px',window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height'));
},700);
.box{
width:100%;
height:auto;
border:1px solid red;
position:relative;
}
<div id="content">
</div>
I see that you are creating your imgNode on a fly using ternary which means you do not have it pre-created in your HTML. So for that, you can use the solution as below by creating an Image constructor.
const images = [
"https://via.placeholder.com/150",
"https://via.placeholder.com/110/0000FF/808080%20?Text=Digital.com",
"https://via.placeholder.com/80/0000FF/808080%20?Text=Digital.com"
];
const img = new Image();
img.addEventListener("load", (ev) => {
console.log(ev);
document.getElementById(
"content"
).innerHTML = `<div class="box">${ev.target}</div>`;
const height = window
.getComputedStyle(document.querySelector(".box"), null)
.getPropertyValue("height");
const imageWidth = window
.getComputedStyle(document.querySelector(".box img"), null)
.getPropertyValue("width");
console.log("height", height, "width", imageWidth);
const wrapImage = `<div style="width:calc(${imageWidth} + 10px);height:calc(${height} + 10px);position:absolute;left:0;top:0;border:1px solid yellow;"></div>`;
document.querySelector(".box").insertAdjacentHTML("beforeend", wrapImage);
});
img.src = `${images[Math.floor(Math.random() * images.length)]}`;

Adding a value to a hidden text box

I'm trying to add an image id value to a hidden text box whenever drawX is executed and and make it null when clear is executed. The way my program should work is that it should only draw an x on one image at a time. So whenever that image is selected it will send that image's id to the hidden text box that I named with an id of sendServ . The way I have it written right now, I don't think id is being passed to my drawX function in my OptionClick function. I'm not exactly sure how to get it to work. Maybe there is a simpler way by just using EventListener but I'm not sure. Any help would be appreciated, thank you.
Edit: I decided to add a snippet with a dummy array so it might be easier to help me.
let index = 0;
var hdnName = document.getElementById("sendServ");
const display = "table"; // or "grid" if horizontal, but this migh depend where you place the rest of the code, cause i added the style to the body
const x = 0;
const y = 0;
const images = {
height: 50,
width: 50,
url: [
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fen%2F8%2F84%2FAssociation_of_Gay_and_Lesbian_Psychiatrists_logo.jpg&f=1&nofb=1",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fstatic01.nyt.com%2Fnewsgraphics%2F2016%2F07%2F14%2Fpluto-one-year%2Fassets%2Ficon-pluto.png&f=1&nofb=1",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.oFxADNN67dYP-ke5xg7HbQHaHG%26pid%3DApi&f=1",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.glassdoor.com%2Fsqll%2F1065746%2Felevation-church-squarelogo-1453223965790.png&f=1&nofb=1"
],
id: [0, 1, 2, 3]
};
function createHTML() {
console.log("E: Execute & R: Request & I: Informative");
//loop to go true all images
document.body.style.display = display;
for (const image of images.url) {
//each image will correspond to a canvas element
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
//each canvas element will has is own properties (in this case all the same)
canvas.id = "option" + [index];
canvas.height = images.height;
canvas.width = images.width;
canvas.style.padding = "10px";
//function to get the corresponded image of that particular canvas element
drawImages(canvas);
//add an event listener for when a user click on the particular canvas
canvas.addEventListener("click", optionClick, false);
//all html part was handle we can append it to the body
document.body.appendChild(canvas);
index++;
}
}
function drawImages(canvas) {
//we need to use the getContext canvas function to draw anything inside the canvas element
const ctx = canvas.getContext("2d");
const background = new Image();
//This is needed because if the drawImage is called from a different place that the createHTML function
//index value will not be at 0 and it will for sure with an heigher id that the one expected
//so we are using regex to remove all letters from the canvas.id and get the number to use it later
index = canvas.id.replace(/\D/g, "");
//console.log('E: Drawing image ' + index + ' on canvas ' + canvas.id);
//get the image url using the index to get the corresponded image
background.src = images.url[index];
//no idea why but to place the image, we need to use the onload event
//https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
background.onload = function() {
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
};
}
function drawX(canvas, item) {
const ctx = canvas.getContext("2d");
// console.log("E: Placing X on canvas " + canvas.id);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(images.width, images.height);
ctx.moveTo(images.height, 0);
ctx.lineTo(0, images.width);
ctx.closePath();
ctx.stroke();
hdnName.value = item;
}
function clear(canvas) {
//console.log("E: clearing canvas " + canvas.id);
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
drawImages(canvas);
hdnName.value = null;
}
function optionClick(e) {
log = true;
var index = 0;
const canvas = document.getElementsByTagName("canvas");
for (const option of canvas) {
if (log)
console.log("I: User clicked at option " + e.target.id + ":" + option.id);
log = false;
if (e.target.id === option.id) {
// console.log('R: Drawing request at canvas ' + option.id);
var item = images.id[index];
console.log(item);
drawX(option, item);
} else {
// console.log('R: Clearing request at canvas ' + option.id);
clear(option);
}
index++;
}
}
//We start by calling createHTML (that will handle with all HTML elements)
window.onload = createHTML;
canvas.suiteiCanvas {
height: auto;
width: auto;
max-height: 200px;
max-width: 150px;
margin-left: 100px;
margin-right: 100px;
border: 3px solid rgb(20, 11, 11);
}
#draw-btn {
font-size: 14px;
padding: 2px 16px 3px 16px;
margin-bottom: 8px;
}
img.new {
height: auto;
width: auto;
max-height: 200px;
max-width: 150px;
margin-left: 100px;
margin-right: 100px;
border: 3px solid rgb(20, 11, 11);
}
<body></body>
<input type="text" id="sendServ">

HTML CANVAS - Preload Issue or OnLoad issue - Why do I have to click twice?

I have an HTML page with 2 canvases side-by-side. The left one has a clickable upper region. The right one is where all the drawing takes place. I want the user to click the region on the left, which will load a new image on the right, and replace the one that is already there, but I have to click twice for the new image to show up. Why is this? See code.
THE HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
#centerAll {
margin-left:auto;
margin-right:auto;
width:1300px;
}
</style>
</head>
<body>
<div id="centerAll">
<canvas id="TheLeftCanvas" width="300" height="500"
style="border:2px solid #999999;"></canvas>
<canvas id="TheRightCanvas" width="900" height="500"
style="border:2px solid #999999;"></canvas>
<script type="text/javascript" src="whyClickTwiceForImage.js">
</script>
</div>
</body>
</html>
AND THE JAVASCRIPT
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
canvasApp();
}
function canvasApp() {
var rightCanvas = document.getElementById("TheRightCanvas");
//THE EMPTY CANVAS ON THE RIGHT, WHICH DRAWS THINGS
var rightCtx = rightCanvas.getContext("2d");
var leftCanvas = document.getElementById("TheLeftCanvas");
//THE EMPTY CANVAS ON THE LEFT, WHICH HANDLES USER CLICKS
var leftCtx = leftCanvas.getContext("2d");
var currentMouseXcoor = 0;
var currentMouseYcoor = 0;
var imagesToLoad = 0; //USED TO PRE-LOAD SOME OTHER VISUALS, BEFORE THE USER STARTS
var imagesLoaded = 0;
var picturesTheUserCanChoose = ["pic01.png", "pic02.png",
"pic03.png", "pic04.png", "pic05.png"];
var nameOfPicTheUserChose = "pic05.png"; //LET'S JUST SAY "pic05.png" IS A PLACEHOLDER PICTURE... TO START OFF
var legitMouseClick = 0; //DID THE USER CLICK IN THE UPPER REGION OF THE LEFT CANVAS?
var loaded = function(){ // "LOADED" AND "LOAD IMAGE" ARE USED TO PRELOAD ALL THOSE OTHER VISUALS BEFORE THE USER STARTS
imagesLoaded += 1;
if(imagesLoaded === imagesToLoad){
imagesToLoad = 0;
imagesLoaded = 0;
drawScreen(); // OK... ALL LOADED.... SO DRAW THE SCREEN
}
}
var loadImage = function(url){ // "LOADED" AND "LOAD IMAGE" ARE USED TO PRELOAD ALL THOSE OTHER PICS BEFORE THE USER STARTS
var image = new Image();
image.addEventListener("load",loaded);
imagesToLoad += 1; // ADD THE NUMBER TO THE IMAGES NEEDED TO BE LOADED
image.src = url;
return image; // ...AND RETURN THE IMAGE
}
//--------------------------------------------------------------
leftCanvas.addEventListener('mouseup', function(evt) { var
mousePos = doMouseUp(leftCanvas, evt);
currentMouseXcoor = mousePos.x; currentMouseYcoor =
mousePos.y; processMousePosition();}, false);
//--------------------------------------------------------------
function drawScreen(){
clearScreen();
rightCtx.drawImage(picture1,0,0,100,100);
}
//THIS FUNCTION PRESUMABLY LOADS IMAGES ON-THE-FLY... BUT WHY DOES THE LEFT CANVAS REGION HAVE TO BE CLICKED TWICE FOR THE NEW IMAGE TO SHOW?
function processMousePosition() {
if(currentMouseYcoor >= 0 && currentMouseYcoor <= 50){
//IF THE CLICK IS IN THE UPPER REGION OF THE LEFT CANVAS
nameOfPicTheUserChose = picturesTheUserCanChoose[0];
//WE'LL SAY THE USER CHOSE THE VERY FIRST PIC IN THE ARRAY
picture1.src = ("picturesFolder/"+ nameOfPicTheUserChose);
picture1.onload = legitMouseClick = 1;//I JUST MADE UP FOR SOMETHING TO HAPPEN WHEN THE NEW PICTURE LOADS???
alert(nameOfPicTheUserChose); // THE ALERT CORRECTLY SHOWS THE NAME OF THE FIRST PIC IN THE ARRAY
}
drawScreen();
}
function doMouseUp(leftCanvas, evt){
var rect = leftCanvas.getBoundingClientRect();
return { x: evt.clientX - rect.left, y: evt.clientY - rect.top};
}
function clearScreen(){
rightCtx.clearRect(0, 0, 900, 500);
leftCtx.clearRect(0, 0, 300, 500);
}
//var someOtherVisual1 =
//loadImage("backgroundArtFolder/someOtherVisual1.jpg");
//var someOtherVisual2 =
//loadImage("backgroundArtFolder/someOtherVisual2.png");
//var someOtherVisual3 =
//loadImage("backgroundArtFolder/someOtherVisual3.png");
//var someOtherVisual4 =
//loadImage("backgroundArtFolder/someOtherVisual4.png");
//var someOtherVisual5 =
//loadImage("backgroundArtFolder/someOtherVisual5.png");
var picture1 = loadImage("picturesFolder/pic05.png");
//LET'S JUST PRELOAD "pic05.png" AS A PLACEHOLDER... TO START OFF
}
You can change the image load on click in js file picture1.src = ("picturesFolder/"+ nameOfPicTheUserChose); to picture1 = loadImage("picturesFolder/"+nameOfPicTheUserChose); and picture1.onload = legitMouseClick = 1; to 'legitMouseClick = 1'

onClick event on image while already moving

I'm trying to make an image that moves to the right on my website. When you click the image, it should move to the left. For now, this doesn't happen, any ideas? If possible, in pure Javascript and no Jquery ;)
Also, if you click the image for a second time, it should move to the right again. Every consecutive time, the image should move to the other side. I guess this would be best with a for-loop?
<script type"text/javascript">
window.onload = init;
var winWidth = window.innerWidth - movingblockobject.scrollWidth; //get width of window
var movingblock = null //object
movingblock.onclick = moveBlockLeft();
function init() {
movingblock = document.getElementById('movingblockobject'); //get object
movingblock.style.left = '0px'; //initial position
moveBlockRight(); //start animiation
}
function moveBlockRight() {
if (parseInt(movingblock.style.left) < winWidth) { // stop function if element touches max window width
movingblock.style.left = parseInt(movingblock.style.left) + 10 + 'px'; //move right by 10px
setTimeout(moveBlockRight,20); //call moveBlockRight in 20 msec
} else {
return;
}
}
function moveBlockLeft () {
movingblock.style.right = parseInt(movingblock.style.right) + 10 + 'px'
}
</script>
Please first go through the Basics of javascript before trying out something .
window.onload = init;
var winWidth = window.innerWidth;
var movingblock = null;
var intervalid = null;
var isLeft = false;
function init() {
console.log('Init');
movingblock = document.getElementById('movingblockobject');
movingblock.style.left = '0px';
intervalid = setInterval(function() {
moveBlock(true);
}, 2000);
movingblock.onclick = function() {
moveBlock(false);
};
}
function moveBlock(isSetInterval) {
if (!isSetInterval)
isLeft = !isLeft;
if (parseInt(movingblock.style.left) < winWidth) {
if (isLeft)
movingblock.style.left = parseInt(movingblock.style.left) - 10 + 'px';
else
movingblock.style.left = parseInt(movingblock.style.left) + 10 + 'px';
} else {
movingblock.style.left = '0px';
}
}
function moveBlockLeft() {
clearInterval(intervalid);
movingblock.style.right = parseInt(movingblock.style.right) + 10 + 'px';
intervalid = setInterval(moveBlockRight, 20);
}
<div id="movingblockobject" style="width:50px;height:50px;border:solid;position: absolute;">
var movingblock = null
this are mistakes you have delclared it as null and next line you are binding click event.Also for assigning click event you should assign the name of the function.
movingblock.onclick = moveBlockLeft;
above is basic bug there are lot like the above.I feel Self learning is much better for basics
try yourself.
try the above it will work but please try yourself
You should CSS3 transition, works like a charm. Just toggle a class "right"
HTML:
<html>
<head>
<style>
#movingblockobject{
width: 40px;
padding: 10px;
position: fixed;
height:10px;
left:0px;
-webkit-transition: left 2s; /* For Safari 3.1 to 6.0 */
transition: left 2s;
}
#movingblockobject.right{
left:200px;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$( document ).ready(function() {
$('#movingblockobject').on('click', function (e) {
$('#movingblockobject').toggleClass("right");
});
});
</script>
</head>
<body>
<div id="movingblockobject" class="demo">add image here</div>
</body>
</html>

Drawing repeatedly updating images to the canvas (Safari blanks out image during loading)

I'm drawing an image onto the background of a canvas. This image refreshes every second, but the canvas needs to be redrawn more often than that, every 0.5 seconds. The problem I seem to be running into is that Safari flickers when updating the canvas because it appears to lose the image data from the bgImg variable. Firefox works as expected and no flicker occurs.
Does anyone have any clue as to how to avoid this? Am I missing something really obvious?
To test this code, simply paste the entire code below into an html file and load with your browser. What it should do is:
create a canvas
load an image every second
redraw the canvas every 500ms, using the image as a background.
Here's the code:
<html>
<head>
<script type="text/javascript">
var bgImg = new Image();
var firstload = false;
var cv;
var ctx;
var updateBackground = function() {
bgImg.onload = function() {
firstload = true;
console.log("image loaded. Dimensions are " + bgImg.width + "x" + bgImg.height);
}
bgImg.src = "http://mopra-ops.atnf.csiro.au/TOAD/temp.php?" + Math.random() * 10000000;
setTimeout(updateBackground, 1000);
}
var initGraphics = function() {
cv = document.getElementById("canvas");
ctx = cv.getContext("2d");
cv.width = cv.clientWidth;
cv.height = cv.clientHeight;
cv.top = 0;
cv.left = 0;
}
var drawStuff = function() {
console.log("Draw called. firstload = " + firstload );
ctx.clearRect(0, 0, cv.width, cv.height);
if ( firstload == true) {
console.log("Drawing image. Dimensions are " + bgImg.width + "x" + bgImg.height);
try {
ctx.drawImage(bgImg, 0, 0);
} catch(err) {
console.log('Oops! Something bad happened: ' + err);
}
}
setTimeout(drawStuff, 500);
}
window.onload = function() {
initGraphics();
setTimeout(updateBackground, 1000);
setTimeout(drawStuff, 500);
}
</script>
<style>
body {
background: #000000;
font-family: Verdana, Arial, sans-serif;
font-size: 10px;
color: #cccccc;
}
.maindisplay {
position:absolute;
top: 3%;
left: 1%;
height: 96%;
width: 96%;
text-align: left;
border: 1px solid #cccccc;
}
</style>
</head>
<body>
<div id="myspan" style="width: 50%">
<canvas id="canvas" class="maindisplay"></canvas>
</div>
</body>
</html>
Your problem is that you are drawing bgImg while it's loading. Webkit does not cache the old image data while loading a new image; it wipes out the image as soon as a new .src is set.
You can fix this by using two images, using the last-valid-loaded one for drawing while the next one is loading.
I've put an example of this online here: http://jsfiddle.net/3XW8q/2/
Simplified for Stack Overflow posterity:
var imgs=[new Image,new Image], validImage, imgIndex=0;
function initGraphics() {
// Whenever an image loads, record it as the latest-valid image for drawing
imgs[0].onload = imgs[1].onload = function(){ validImage = this; };
}
function loadNewImage(){
// When it's time to load a new image, pick one you didn't last use
var nextImage = imgs[imgIndex++ % imgs.length];
nextImage.src = "..."+Math.random();
setTimeout(loadNewImage, 2000);
}
function updateCanvas(){
if (validImage){ // Wait for the first valid image to load
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(validImage, 0, 0);
}
setTimeout(updateCanvas, 500);
}

Categories