Why image is not changing on button click? - javascript

Could you please tell me why my image is not change on button click here is my code
http://plnkr.co/edit/zQPp1vya27a5UaCJmbE7?p=preview
<button ng-click="clik()">chnage image</button>
$scope.clik = function(){
setTimeout(function (){
alert('xxx')
$scope.ca = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTQDjJroJg1iyhupdjD6h3xslZw7UGyza9Fafv05zjlbwoQt6_D"
},1000)
}

You have two problems. The first is you should be using $timeout so you do not have to tell angular it needs to go through a digest cycle and update all the bindings. So anywhere you have setTimeout(...) use $timeout(...)
setTimeout(function (){
alert('xxx')
$scope.ca = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTQDjJroJg1iyhupdjD6h3xslZw7UGyza9Fafv05zjlbwoQt6_D"
},1000)
//would be
$timeout(function (){
alert('xxx')
$scope.ca = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTQDjJroJg1iyhupdjD6h3xslZw7UGyza9Fafv05zjlbwoQt6_D"
},1000)
The second problem is you do not wait for the image to load before trying to draw it:
setTimeout(()=>{
resetImage();
},0)
This is not long enough to allow the image to load. Instead use a load event to detect when it has loaded and then run resetImage().
angular.element("#image").bind('load', resetImage);
Demo
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $timeout) {
$scope.ca = 'https://media.glassdoor.com/brand-logo/white-logotype/glassdoor-logo.jpg'
$scope.imageArray = ['https://pbs.twimg.com/profile_images/2504398687/344204969_400x400.jpg', 'https://media.glassdoor.com/brand-logo/white-logotype/glassdoor-logo.jpg'];
$scope.getImage = function(data) {
return data;
};
$scope.onImageClick = function(data, index) {
$scope.ca = data;
$scope.currentImageIndex = index;
};
$scope.clik = function() {
$timeout(function() {
$scope.ca = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTQDjJroJg1iyhupdjD6h3xslZw7UGyza9Fafv05zjlbwoQt6_D";
}, 1000);
};
})
app.directive('imageViewer', function($timeout) {
return {
restrict: 'EA',
template: '<div style="padding:10px;">\
<button id="girardir" class="btn btn-primary btn-sm" ng-disabled="noImage"><span class="glyphicon glyphicon-menu-left"> </span> Rotate Anti-clockwise</button>\
<button id="giraresq" class="btn btn-primary btn-sm" ng-disabled="noImage">Rotate Clockwise <span class="glyphicon glyphicon-menu-right"> </span></button>\
<button id="zoomIn" class="btn btn-info btn-sm" ng-disabled="noImage"><span class="glyphicon glyphicon-zoom-in"> </span> Zoom In</button>\
<button id="zoomOut" class="btn btn-info btn-sm" ng-disabled="noImage"><span class="glyphicon glyphicon-zoom-out"> </span> Zoom Out</button>\
</div>\
<div id="image-zoom" style="padding:10px;">\
<h2 class="text-center text-danger" id="error-message" style="border:1px solid #000;display:none;padding:20px">Image Not Available</h2>\
<canvas id="canvas" height="350" data-girar="0" style="border:1px solid #000;z-index:555555;cursor:grab;position:inherit;">sdsd</canvas>\
<img ng-src="{{image}}" id="image" (load)="resetImage()" style="display:none" /> </div>',
scope: {
src: '='
},
link: function(scope, element, attr) {
scope.$watch('src', function(src) {
if (src) {
scope.image = src;
}
});
scope.noImage = false;
var canvas = document.getElementById('canvas');
var image = document.getElementById('image');
var element = canvas.getContext("2d");
var angleInDegrees = 0;
var zoomDelta = 0.1;
var currentScale = 1;
var currentAngle = 0;
var canvasWidth = 500;
var novosDadosTRBL;
var novosDadosWH;
var novosDadosW;
var novosDadosH;
var startX, startY, isDown = false;
scope.flag = 1;
$timeout(function() {
canvas.width = angular.element('#image-zoom').width();
canvas.width = canvasWidth;
}, 0);
angular.element('#carregar').click(function() {
angular.element('#image').on('load', resetImage())
.on('error', function() {
angular.element('#canvas').hide();
scope.noImage = true;
angular.element('#error-message').show();
console.log("error loading image");
});
});
//add image load event
angular.element("#image").bind('load', resetImage);
function resetImage() {
image = document.getElementById('image');
element = canvas.getContext("2d");
angleInDegrees = 0;
currentScale = 1;
currentAngle = 0;
if (scope.flag) {
scope.flag = 0;
drawImage();
element.translate(canvas.width / 2, canvas.height / 2);
$timeout(function() {
angular.element('#canvas').attr('data-girar', 0);
drawImage();
}, 0);
} else {
element.translate(0, 0);
angular.element('#canvas').attr('data-girar', 0);
drawImage();
}
};
angular.element('#giraresq').click(function() {
angleInDegrees = 90;
currentAngle += angleInDegrees;
drawImage();
});
angular.element('#girardir').click(function() {
angleInDegrees = -90;
currentAngle += angleInDegrees;
drawImage();
});
angular.element('#zoomIn').click(function() {
currentScale += zoomDelta;
drawImage();
});
angular.element('#canvas').bind('mousewheel DOMMouseScroll', function(event) {
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
currentScale += zoomDelta;
drawImage();
} else {
if (currentScale - zoomDelta - 0.1 > 0) {
currentScale -= zoomDelta;
drawImage();
}
}
});
angular.element('#zoomOut').click(function() {
if (currentScale > 0.12) {
currentScale -= zoomDelta;
}
drawImage();
});
canvas.onmousedown = function(e) {
var pos = getMousePos(canvas, e);
startX = pos.x;
startY = pos.y;
isDown = true;
}
canvas.onmousemove = function(e) {
if (isDown === true) {
var pos = getMousePos(canvas, e);
var x = pos.x;
var y = pos.y;
element.translate(x - startX, y - startY);
drawImage();
startX = x;
startY = y;
}
}
window.onmouseup = function(e) {
isDown = false;
}
function drawImage() {
clear();
element.save();
element.scale(currentScale, currentScale);
element.rotate(currentAngle * Math.PI / 180);
element.drawImage(image, -image.width / 2, -image.height / 2);
element.restore();
}
function clear() {
element.clearRect(-2000, -2000, 5000, 5000);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
}
}
});
.error {
corder: 1px solid red;
}
.imgContainer ul {
display: flex;
margin: 0;
padding: 0;
list-style: none;
overflow-x: scroll;
width: 100%;
}
.imgContainer ul li {
margin-left: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
<div class="imgContainer" ng-if="imageArray && imageArray.length">
<ul>
<li ng-repeat="img in imageArray"><img data-ng-src="{{getImage(img)}}" width="100" height="100" ng-click="onImageClick(img,$index)" /></li>
</ul>
</div>
<image-viewer src="ca"></image-viewer>
<button ng-click="clik()">chnage image</button>
</div>
Plunker if needed

Related

Draggable text on canvas

I'm making a whiteboard app where I want to drag text around the whiteboard with my mouse. Below is my dragText() so far where I handle mouse events etc. I tested click and move mouse events, and they both work, however the function still doesn't work as intended (I can't drag the text). I am out of ideas.
Also I noticed that in the function handleMouseDown, whenever I click somewhere on canvas where text coordinates are out of bounds, everything works fine there, but whenever I click on the text (and so the if statement in the for loop becomes true) suddenly whole canvas returns true (function textInBounds). Why is that?
function dragText() {
var canvas = document.getElementById('board'),
ctx = canvas.getContext('2d'),
font = '14px sans-serif';
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var texts = [];
texts.push({ text: "Hello", x: 20, y: 20 });
var StartX;
var StartY;
for (var i = 0; i < texts.length; i++) {
var text = texts[i];
ctx.position = 'absolute';
ctx.font = font;
ctx.fillText(text.text, text.x, text.y);
}
canvas.addEventListener('mousedown', function(e) {
handleMouseDown(e);
})
function handleMouseDown(e) {
e.preventDefault();
StartX = parseInt(e.clientX - canvas.getBoundingClientRect().left);
StartY = parseInt(e.clientY - canvas.getBoundingClientRect().top);
for (var i = 0; i < texts.length; i++) {
if (textInBounds(StartX, StartY, i)) {
selectElement(i);
canvas.addEventListener('mousemove', function(e) {
handleMouseMove(e);
})
} else {
return;
}
}
}
var selectedElement;
function selectElement(element) {
selectedElement = element;
}
function textInBounds(x, y, i) {
var text = texts[i];
return (x <= (text.x + ctx.measureText(text.text).width) && x > text.x);
}
function handleMouseMove(e) {
if (selectedElement < 0) {
return;
}
e.preventDefault();
var MouseX, MouseY
MouseX = parseInt(e.clientX - canvas.getBoundingClientRect().left);
MouseY = parseInt(e.clientY - canvas.getBoundingClientRect().top);
var dx = MouseX - StartX;
var dy = MouseX - StartY;
StartX = MouseX;
StartY = MouseX;
var text = texts[selectedElement];
text.x += dx;
text.y += dy;
}
{
function handleMouseUp(e) {
e.preventDefault();
selectedElement = -1;
}
}
}
HTML
render()
{
return(
<div class="sketch" id="sketch">
<canvas className="board" id="board"> </canvas>
</div>
)
}
CSS
.board
{
width: 100%;
height: 100%;
}
.sketch
{
width: 100%;
height: 100%;
}

Error when working with HTML canvas - Uncaught TypeError: Cannot read property 'start' of undefined

I have written a code for a game based on a html canvas. When I run it, I do not get the canvas game loaded onto the canvas. Instead I get the below error in my console:-
Uncaught TypeError: Cannot read property 'start' of undefined
I have given my code below. Can someone please explain me what might be the reason?
<script>
var context;
var canvas;
var ctx;
var speed = urlParam('speed');
if (speed == null)
speed = 40
$('#speed').val(speed);
calculateBubble(parseInt(speed));
var redSBLatter;
var redSBFormer;
var redSBWindowFormer;
var redSBWindowLatter;
var blueSB;
var blueSWindow;
function startGame(bubbleLength, windowLength) {
redSBWindowFormer = new slidingWindow(60, windowLength * 2, "black", 5, 120);
redSBWindowLatter = new slidingWindow(60, 40, "black", 5, 80);
redSBFormer = new component(30, bubbleLength, "red", 20, 120);
redSBLatter = new component(30, 30, "red", 20, 90);
blueSWindow = new slidingWindow(60, 70, "black", 120, 10);
blueSB = new component(20, 40, "blue", 140, 20);
myGameArea.start();
}
var myGameArea = {
start: function () {
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
//myCanvas.width = "480";
//myCanvas.height = "480";
document.body.insertBefore(canvas, document.body.childNodes[0]);
interval = setInterval(updateGameArea, 20);
},
clear: function () {
context.clearRect(0, 0, canvas.width, canvas.height);
}
}
function urlParam(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
}
else {
return decodeURI(results[1]) || 0;
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function () {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function () {
this.x += this.speedX;
this.y += this.speedY;
}
}
function slidingWindow(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function () {
ctx = myGameArea.context;
ctx.beginPath();
//ctx.globalAlpha = 0.2;
ctx.lineWidth = "3";
ctx.strokeStyle = color;
ctx.rect(this.x, this.y, this.width, this.height);
ctx.stroke();
}
this.newPos = function () {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
redSBLatter.newPos();
redSBLatter.update();
redSBFormer.newPos();
redSBFormer.update();
redSBWindowLatter.newPos();
redSBWindowLatter.update();
redSBWindowFormer.newPos();
redSBWindowFormer.update();
blueSB.newPos();
blueSB.update();
blueSWindow.newPos();
blueSWindow.update();
}
function redmoveup() {
redSBLatter.speedY = -1;
redSBFormer.speedY = -1;
redSBWindowLatter.speedY = -1;
redSBWindowFormer.speedY = -1;
}
function bluemoveup() {
blueSB.speedY = -1;
blueSWindow.speedY = -1;
}
function redmovedown() {
redSBLatter.speedY = 1;
redSBFormer.speedY = 1;
redSBWindowLatter.speedY = 1;
redSBWindowFormer.speedY = 1;
}
function bluemovedown() {
blueSB.speedY = 1;
blueSWindow.speedY = 1;
}
function redmoveleft() {
redSBLatter.speedX = -1;
redSBFormer.speedX = -1;
redSBWindowLatter.speedX = -1;
redSBWindowFormer.speedX = -1;
}
function bluemoveleft() {
blueSB.speedX = -1;
blueSWindow.speedX = -1;
}
function redmoveright() {
redSBLatter.speedX = 1;
redSBFormer.speedX = 1;
redSBWindowLatter.speedX = 1;
redSBWindowFormer.speedX = 1;
}
function bluemoveright() {
blueSB.speedX = 1;
blueSWindow.speedX = 1;
}
function clearmove() {
redSBLatter.speedX = 0;
redSBLatter.speedY = 0;
redSBFormer.speedX = 0;
redSBFormer.speedY = 0;
redSBWindowLatter.speedX = 0;
redSBWindowLatter.speedY = 0;
redSBWindowFormer.speedX = 0;
redSBWindowFormer.speedY = 0;
blueSB.speedX = 0;
blueSB.speedY = 0;
blueSWindow.speedX = 0;
blueSWindow.speedY = 0;
}
/** function calculateBubble() {
var kmh = document.getElementById("speed").value;
if (kmh <= 0) {
var bubble = 5.84;
var window = bubble * 5;
document.getElementById("bubble").innerHTML = bubble;
document.getElementById("window").innerHTML = window;
return startGame(20, 20);
}
else {
//var v = getMph(kmh);
var v = kmh / 1.6093;
var feet = 2.2 * v + ((v * v) / 20);
var bubblemeters = feet / 3.28;
var bubble = parseFloat(bubblemeters.toFixed(2));
document.getElementById("bubble").innerHTML = bubble;
calculateWindow(bubble);
return bubblemeters;
}
}**/
function calculateBubble(kmh) {
var v = kmh / 1.6093;
var feet = 2.2 * v + ((v * v) / 20)
var meters = feet / 3.28;
$('#sBubble').empty();
$('#sBubble').append("Safety bubble : " + meters.toFixed(2) + " m");
calculateWindow(meters);
}
function calculateWindow(bubble) {
var windowMeters = bubble + 5;
var window = parseFloat(windowMeters.toFixed());
document.getElementById("window").innerHTML = window;
startGame(bubble, window);
}
</script>
<style type="text/css">
#canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
.grid-container {
display: grid;
grid-template-columns: auto auto auto;
background-color: #2196F3;
padding: 10px;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
font-size: 30px;
text-align: center;
}
</style>
<!DOCTYPE html>
<html>
<head>
<title>Staging Area Simulation</title>
<meta charset="UTF-8">
<script src="public_html/jquery.js"></script>
</head>
<!--<body onload="startGame()">-->
<body>
<div class="grid-container">
<div>
<canvas id="canvas" width="480" height="480">
</canvas>
</div>
<div>
<h3>Enter Parameters</h3>
<p id="sBubble">Safety bubble : 0.0 m</p>
Sliding Window :<p id="window"></p>
<form method="get" id="form">
speed : <input type="text" id="speed" name="speed" /> <br /><br />
Vehicle Length : <input type="text" id="vLength" name="vLength" value="3.84m" disabled />
<br /><br />
Vehicle Width : <input type="text" id="vWidth" name="vWidth" value="1.74m" disabled />
<br /><br />
<button name="data" type="submit">Calculate</button>
</form>
</div>
<div style="text-align:center;width:480px;">
<h3>
Red Controllers </h3>
<button onmousedown="redmoveup()" onmouseup="clearmove()">UP</button><br><br>
<button onmousedown="redmoveleft()" onmouseup="clearmove()">LEFT</button>
<button onmousedown="redmoveright()" onmouseup="clearmove()">RIGHT</button><br><br>
<button onmousedown="redmovedown()" onmouseup="clearmove()">DOWN</button>
</div>
<div style="text-align:center;width:480px;">
<h3> Blue Controllers</h3>
<button onmousedown="bluemoveup()" onmouseup="clearmove()">UP</button><br><br>
<button onmousedown="bluemoveleft()" onmouseup="clearmove()">LEFT</button>
<button onmousedown="bluemoveright()" onmouseup="clearmove()">RIGHT</button><br><br>
<button onmousedown="bluemovedown()" onmouseup="clearmove()">DOWN</button>
</div>
</div>
</body>
</html>

How to label boxes created on JavaScript canvas?

I have a canvas where I can draw boxes, and then save the x-y coordinates and width and height of these boxes into JSON format. However, I would like to know if it's possible to perhaps have a field where I can enter a unique name for each one of these objects (eg. bluecar, redcar etc.), in which the name will also appear in the JSON output? As shown in the JSON output below, the coordinates and other information are appearing correctly but I'd like to include names for the objects to differentiate them between the other objects.
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
var canvas2 = document.getElementById("canvas2");
var context2 = canvas2.getContext('2d');
let isDrawing = false;
const annotation = {
x: 0,
y: 0,
w: 0,
h: 0,
printCoordinates: function() {
console.log(`X: ${this.x}px, Y: ${this.y}px, Width: ${this.w}px, Height: ${this.h}px`);
}
};
let boundingBoxes = [];
function handleMouseDown(e) {
start = oMousePos(canvas2, e);
isDrawing = true;
//console.log(start.x, start.y);
canvas2.style.cursor = "crosshair";
}
function handleMouseMove(e) {
if (isDrawing) {
m = oMousePos(canvas2, e);
draw();
}
}
function handleMouseUp(e) {
canvas2.style.cursor = "default";
isDrawing = false;
const box = Object.create(annotation);
box.x = o.x;
box.y = o.y;
box.w = o.w;
box.h = o.h;
boundingBoxes.push(box);
draw();
box.printCoordinates();
console.log(boundingBoxes)
}
canvas2.addEventListener("mousedown", handleMouseDown);
canvas2.addEventListener("mousemove", handleMouseMove);
canvas2.addEventListener("mouseup", handleMouseUp);
function draw() {
o.x = start.x; // start position of x
o.y = start.y; // start position of y
o.w = m.x - start.x; // width
o.h = m.y - start.y; // height
context2.clearRect(0, 0, canvas2.width, canvas2.height); //////***********
// draw all the rectangles saved in the rectsRy
boundingBoxes.map(r => {
drawRect(r)
})
// draw the actual rectangle
drawRect(o);
}
function drawRect(o) {
context2.strokeStyle = "limegreen";
context2.lineWidth = 2;
context2.beginPath(o);
context2.rect(o.x, o.y, o.w, o.h);
context2.stroke();
}
function oMousePos(canvas2, evt) {
let ClientRect = canvas2.getBoundingClientRect();
return {
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}
document.getElementById('save').addEventListener('click', function() {
// retrieve the canvas data
var canvasContents = canvas.toDataURL(); // a data URL of the current
// canvas
var string = JSON.stringify(boundingBoxes, null, 2);
// create a blob object representing the data as a JSON string
var file = new Blob([string], {
type: 'application/json'
});
// trigger a click event on an <a> tag to open the file explorer
var a = document.createElement('a');
a.href = URL.createObjectURL(file);
a.download = 'data.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Import Image: <input type="file" id="fileUpload" name="fileUpload" multiple/>
<p>
<div id="buttons1">
<button id="reset" onclick="resetcanvas()">Reset Annotations</button> &nbsp
<button id="save">
<span>Export Annotations</span>
</button>
<div id="canvases" align="middle" style="position:relative; width:1580px; height:700px; overflow: scroll; ">
<canvas id="canvas2" align="middle" style="z-index: 1; position: absolute; left: 125px; top: 0px; "></canvas>
<canvas id="canvas" align="middle" style="z-index: 0; position: absolute; left: 125px; top: 0px; "></canvas>
</div>
<p></p>
<br>
<span></span>
</div>
<p></p>
<div id="button ">
</div>
JSON Output:
[
{
"x": 356,
"y": 235,
"w": -105,
"h": -146
},
{
"x": 185,
"y": 238,
"w": -51,
"h": -93
}
]
Any help will be much appreciated, thank you!
I added a few variables to bypass your errors... I assumed that was just a copy/paste error.
On the handleMouseUp you can add a box.name = "Name"; to include a name
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
var canvas2 = document.getElementById("canvas2");
var context2 = canvas2.getContext('2d');
let isDrawing = false;
const annotation = {
x: 0, y: 0, w: 0, h: 0,
printCoordinates: function() {
console.log(`X: ${this.x}px, Y: ${this.y}px, Width: ${this.w}px, Height: ${this.h}px`);
}
};
var o = annotation;
var start;
let boundingBoxes = [];
function handleMouseUp(e) {
canvas2.style.cursor = "default";
isDrawing = false;
const box = Object.create(annotation);
box.x = o.x;
box.y = o.y;
box.w = o.w;
box.h = o.h;
box.name = "Name";
boundingBoxes.push(box);
draw();
box.printCoordinates();
//console.log(boundingBoxes)
}
function handleMouseDown(e) {
start = oMousePos(canvas2, e);
isDrawing = true;
//console.log(start.x, start.y);
canvas2.style.cursor = "crosshair";
}
function handleMouseMove(e) {
if (isDrawing) {
m = oMousePos(canvas2, e);
draw();
}
}
canvas2.addEventListener("mousedown", handleMouseDown);
canvas2.addEventListener("mousemove", handleMouseMove);
canvas2.addEventListener("mouseup", handleMouseUp);
function draw() {
o.x = start.x; // start position of x
o.y = start.y; // start position of y
o.w = m.x - start.x; // width
o.h = m.y - start.y; // height
context2.clearRect(0, 0, canvas2.width, canvas2.height); //////***********
// draw all the rectangles saved in the rectsRy
boundingBoxes.map(r => {
drawRect(r)
})
// draw the actual rectangle
drawRect(o);
}
function drawRect(o) {
context2.strokeStyle = "limegreen";
context2.lineWidth = 2;
context2.beginPath(o);
context2.rect(o.x, o.y, o.w, o.h);
context2.stroke();
}
function oMousePos(canvas2, evt) {
let ClientRect = canvas2.getBoundingClientRect();
return {
x: Math.round(evt.clientX - ClientRect.left),
y: Math.round(evt.clientY - ClientRect.top)
}
}
document.getElementById('save').addEventListener('click', function() {
// retrieve the canvas data
var canvasContents = canvas.toDataURL(); // a data URL of the current
// canvas
var string = JSON.stringify(boundingBoxes, null, 2);
// create a blob object representing the data as a JSON string
var file = new Blob([string], {
type: 'application/json'
});
// trigger a click event on an <a> tag to open the file explorer
var a = document.createElement('a');
a.href = URL.createObjectURL(file);
a.download = 'data.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Import Image: <input type="file" id="fileUpload" name="fileUpload" multiple/>
<p>
<div id="buttons1">
<button id="reset" onclick="resetcanvas()">Reset Annotations</button> &nbsp
<button id="save"><span>Export Annotations</span></button>
<div id="canvases" align="middle" style="position:relative; width:1580px; height:700px; overflow: scroll; ">
<canvas id="canvas2" align="middle" style="z-index: 1; position: absolute; left: 125px; top: 0px; "></canvas>
<canvas id="canvas" align="middle" style="z-index: 0; position: absolute; left: 125px; top: 0px; "></canvas>
</div>
<p></p>
<br>
<span></span>
</div>
<p></p>
<div id="button ">
</div>

Canvas shows but image doesn't render

I've tried making a sprite animation of a rotating book but it doesn't work. The canvas works fine, and another script works but the book script isn't working. The rest of the page works completely fine but I omitted the extra code since they do not need any corrections.
What is the problem? Thank you in advance
function myFunction() {
document.getElementById("changeBox").style.backgroundColor = "black";
document.getElementById("changeBox").style.fontSize = "40px";
document.getElementById("changeBox").style.textAlign = "center";
document.getElementById("showDate").innerHTML = Date();
}
function bookAnimation() {
var book,
bookImage,
canvas;
var c = document.getElementById("Book");
function gameLoop() {
window.requestAnimationFrame(gameLoop);
book.update();
book.render();
}
function sprite(options) {
var that = {},
frameIndex = 0,
tickCount = 0,
ticksPerFrame = options.ticksPerFrame || 0,
numberOfFrames = options.numberOfFrames || 1;
that.context = options.context;
that.width = options.width;
that.height = options.height;
that.image = options.image;
that.update = function() {
tickCount += 1;
if (tickCount > ticksPerFrame) {
tickCount = 0;
if (frameIndex < numberOfFrames - 1) {
frameIndex += 1;
} else {
frameIndex = 0;
}
}
};
that.render = function() {
that.context.clearRect(0, 0, that.width, that.height);
that.context.drawImage(
that.image,
frameIndex * that.width / numberOfFrames,
0,
that.width / numberOfFrames,
that.height,
0,
0,
that.width / numberOfFrames,
that.height);
};
return that;
}
canvas = document.getElementById("bookAnimation");
canvas.width = 100;
canvas.height = 100;
bookImage = new Image();
book = sprite({
context: canvas.getContext("2d"),
width: 1000,
height: 100,
image: bookImage,
numberOfFrames: 10,
ticksPerFrame: 4
});
bookImage.addEventListener("load", gameLoop);
bookImage.src = "E:\Second Year\cwd2018\Book Sprite.png";
}
<div style="background-color:black">
<div style="text-align:center;">
<input type="button" value="Welcome to Login Page" id="changeBox" onclick="myFunction()">
<p id="showDate"></p>
<canvas id="Book" width="200" height="200" style="background-color: yellow"></canvas>
</div>
</div>

Drawing a straight line using mouse events on canvas in javascript

I am trying to draw a straight line on canvas using mouse events.I am new to java script. Can anybody help or refer something from where i can get help?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var bounds = null;
var ctx = null;
var hasLoaded = false;
var startX = 0;
var startY = 0;
var mouseX = 0;
var mouseY = 0;
var isDrawing = false;
var existingLines = [];
function draw() {
ctx.fillStyle = "#333333";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
for (var i = 0; i < existingLines.length; ++i) {
var line = existingLines[i];
ctx.moveTo(line.startX,line.startY);
ctx.lineTo(line.endX,line.endY);
}
ctx.stroke();
if (isDrawing) {
ctx.strokeStyle = "darkred";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(startX,startY);
ctx.lineTo(mouseX,mouseY);
ctx.stroke();
}
}
function onmousedown(e) {
if (hasLoaded && e.button === 0) {
if (!isDrawing) {
startX = e.clientX - bounds.left;
startY = e.clientY - bounds.top;
isDrawing = true;
}
draw();
}
}
function onmouseup(e) {
if (hasLoaded && e.button === 0) {
if (isDrawing) {
existingLines.push({
startX: startX,
startY: startY,
endX: mouseX,
endY: mouseY
});
isDrawing = false;
}
draw();
}
}
function onmousemove(e) {
if (hasLoaded) {
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;
if (isDrawing) {
draw();
}
}
}
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.onmousedown = onmousedown;
canvas.onmouseup = onmouseup;
canvas.onmousemove = onmousemove;
bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
hasLoaded = true;
draw();
}
</script>
</body>
</html>

Categories