Canvas drawing error - javascript

When I try to draw an image to a Canvas element I get this exeption:
Uncaught Error: INDEX_SIZE_ERR: DOM Exception 1
textureLoadedstaticsprite.js:14
StaticSpritestaticsprite.js:21
(anonymous function)
All both the CanvasRenderingContent and the HTMLImageElement exist.
I just don't get it :S
Here is teh code I'm using:
/**
* Class for drawing static sprites, like trees and blocks
*/
function StaticSprite(args) {
// Private Fields
var texture = new Image();
// Events
function textureLoaded(context) {
console.log(context);
console.log(texture);
context.drawImage(texture, 0, 0, 32, 32);
}
// Constructor
// Add event listeners
texture.addEventListener("load", textureLoaded(this.graphics), false);
// Load texture
texture.src = "img/assets/wall1.png";
if(args != undefined) {
// Set local fields
this.x = args.x || this.x;
this.y = args.y || this.y;
this.z = args.z || this.z;
this.width = args.width || this.width;
this.height = args.height || this.height;
}
this.width = 32;
this.height = 32;
}
// Inherit from GraphicsEntity
StaticSprite.prototype = new GraphicsEntity();
And here is the GraphicsEntity base class, in case you need it :P
/**
* Class for presentation of graphical objects.
*/
function GraphicsEntity(args) {
// Private Fields
var x = 0; // The X-position of the GraphicsEntity relative to it's parent container
var y = 0; // The Y-position of the GraphicsEntity relative to it's parent container
var z = 0; // The Z-position of the GraphicsEntity relative to it's parent container
var width = 0; // The width of the GraphicsEntity
var height = 0; // The height of the GraphicsEntity
// Public Fields
this.DOMElement = null; // Reference to the corresponding HTML Element
this.graphics = null; // The 2D context for rendering 2D onto the element.
this.name = ""; // The name of the GraphicsEntity
// Properties
// The Alpha or transparency value of the GraphicsEntity, 1 is completely opaque, 0 is completely transparent.
Object.defineProperty(this, "alpha", {
get: function() { return parseFloat(this.DOMElement.style.opacity); },
set: function(value) { this.DOMElement.style.opacity = value; }
});
// The height of the GraphicsEntity
Object.defineProperty(this, "height", {
get: function() { return height; },
set: function(value) {
height = value; // Set internal width
this.DOMElement.setAttribute("height", height); // Set DOMElement width
}
});
// The width of the GraphicsEntity
Object.defineProperty(this, "width", {
get: function() { return width; },
set: function(value) {
width = value; // Set internal width
this.DOMElement.setAttribute("width", width); // Set DOMElement width
}
});
// The X-position of the GraphicsEntity relative to it's parent container
Object.defineProperty(this, "x", {
get: function() { return x; },
set: function(value) {
x = value; // Set internal X-axis
this.DOMElement.style.left = Math.ceil(x) + "px"; // Set DOMElement X-axis
}
});
// The Y-position of the GraphicsEntity relative to it's parent container
Object.defineProperty(this, "y", {
get: function() { return y; },
set: function(value) {
y = value; // Set internal Y-axis
this.DOMElement.style.top = Math.ceil(y) + "px"; // Set DOMElement Y-axis
}
});
// The Z-position of the GraphicsEntity relative to it's parent container
Object.defineProperty(this, "z", {
get: function() { return z; },
set: function(value) { this.DOMElement.style.zIndex = parseInt(value); }
});
// Constructor
// Get constructor values of use default
if(args) {
x = args.x || x;
y = args.y || y;
z = args.z || z;
width = args.width || width;
height = args.height || height;
}
// Create a new canvas element
this.DOMElement = document.createElement('canvas');
// Set postion
this.DOMElement.style.position = "absolute"; // Positioning style
this.DOMElement.style.left = x + "px"; // X-axis
this.DOMElement.style.top = y + "px"; // Y-axis
this.DOMElement.style.zIndex = z; // Z-Axis
this.DOMElement.width = width;
this.DOMElement.height = height;
// Set opacity/alpha
this.DOMElement.style.opacity = 1;
// Get 2d canvas context
this.graphics = this.DOMElement.getContext('2d');
}

texture.addEventListener("load", textureLoaded(this.graphics), false);
This line tries to add the function returned by textureLoaded(this.graphics) as the event listener. The function returns undefined, so it doesn't quite work out.
Try changing that line to
texture.addEventListener("load", textureLoaded, false);
and replacing the line
function textureLoaded(context) {
With the lines
var context = this.graphics;
function textureLoaded() {

Related

Random movement of circles created by the script

I have a function that craeates divs with a circle.
Now they are all created and appear at the beginning of the page and go further in order.
Next, I need each circle to appear in a random place. I did this.
Now I need all of them to move randomly across the entire page, I have difficulties with this.
Here is an example of how everything works for one element that is already on the page.
https://jsfiddle.net/quej8wko/
But when I add this code, all my created circles don't move.
I get an error:
"message": "Uncaught TypeError: Cannot set properties of null (setting 'willChange')",
This is probably due to the fact that initially there are no circles on the page. How can I connect the code so that all created circles move?
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createDiv(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createDiv(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
clip-path: circle(50%);
height: 40px;
width: 40px;
margin: 20px;
position: absolute;
}
I have modified the snippet which works as you expected.
There was a mistake where you were initializing and creating the object instance only once and none of the div elements that you created inside the setInterval function never got Instantiated.
I think you are just starting out with JavaScript with this sample project.
Below are few suggestions:
Learn to debug the code. You should be using dev tools by making use of debugger statement where it takes you to the source code to analyze the variable scope and stack during the runtime. console.log also helps in few situations.
I could see a lot of confusing naming convention (You have named the create div parameter as id but creating a div class using that id)
Try using ES6 features (class syntax is really good when writing OOP in JS although it's just a syntactic sugar for prototype)
//creating circles
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight + margin;
function createAndInitializeDivObject(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop + "px";
div.style.left = limitedLeft + "px";
document.body.appendChild(div);
var x = new RandomObjectMover(document.querySelector(`.${id}`), window);
x.start();
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i += 1;
createAndInitializeDivObject(`circle${i}`)
}, oneSecond);
//move circles
function RandomObjectMover(obj, container) {
this.$object = obj;
this.$container = container;
this.container_is_window = container === window;
this.pixels_per_second = 250;
this.current_position = { x: 0, y: 0 };
this.is_running = false;
}
// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
this.pixels_per_second = pxPerSec;
}
RandomObjectMover.prototype._getContainerDimensions = function() {
if (this.$container === window) {
return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
} else {
return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
}
}
RandomObjectMover.prototype._generateNewPosition = function() {
// Get container dimensions minus div size
var containerSize = this._getContainerDimensions();
var availableHeight = containerSize.height - this.$object.clientHeight;
var availableWidth = containerSize.width - this.$object.clientHeight;
// Pick a random place in the space
var y = Math.floor(Math.random() * availableHeight);
var x = Math.floor(Math.random() * availableWidth);
return { x: x, y: y };
}
RandomObjectMover.prototype._calcDelta = function(a, b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
var dist = Math.sqrt( dx*dx + dy*dy );
return dist;
}
RandomObjectMover.prototype._moveOnce = function() {
// Pick a new spot on the page
var next = this._generateNewPosition();
// How far do we have to move?
var delta = this._calcDelta(this.current_position, next);
// Speed of this transition, rounded to 2DP
var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
//console.log(this.current_position, next, delta, speed);
this.$object.style.transition='transform '+speed+'s linear';
this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
// Save this new position ready for the next call.
this.current_position = next;
};
RandomObjectMover.prototype.start = function() {
if (this.is_running) {
return;
}
// Make sure our object has the right css set
this.$object.willChange = 'transform';
this.$object.pointerEvents = 'auto';
this.boundEvent = this._moveOnce.bind(this)
// Bind callback to keep things moving
this.$object.addEventListener('transitionend', this.boundEvent);
// Start it moving
this._moveOnce();
this.is_running = true;
}
RandomObjectMover.prototype.stop = function() {
if (!this.is_running) {
return;
}
this.$object.removeEventListener('transitionend', this.boundEvent);
this.is_running = false;
}
// Init it
var x = new RandomObjectMover(document.querySelector(".circle"), window);
// Start it off
x.start();
.circle {
width: 35px;
height: 35px;
border-radius: 35px;
background-color: #ffffff;
border: 3px solid purple;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="circle"></div>
<script src="app.js"></script>
</body>
</html>

Bind event to object in plain JavaScript

I have a <div> element, which should adjust width + height according to the document properties. I need to resize the <div> whenever the user scrolls inside the window.
Is there a possibility to bind the events to this specific object?
var instance = (function() {
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth || 0,
y = w.innerHeight || e.clientHeight || g.clientHeight || 0,
z = Math.max(g.scrollHeight || 0, e.scrollHeight || 0, g.offsetHeight || 0, e.offsetHeight || 0, g.clientHeight || 0, e.clientHeight || 0);
// private
function getMeById(id) {
return d.getElementById(id);
};
// public
return {
updateContainer: function(id) {
console.log('updateContainer');
var container = getMeById(id);
container.style.position = 'absolute';
container.style.width = x + 'px';
container.style.minHeight = z + 'px';
},
bindScroll: function() {
w.addEventListener('scroll', updateContainer(), false);
}
};
})();
instance.updateContainer("test");
/* #TODO: Bind events to object
w.addEventListener('resize', () => {
console.log('resize');
var container = getMeById("test");
updateContainer(container);
}, true);
w.addEventListener('scroll', () => {
console.log('scroll');
var container = getMeById("test");
updateContainer(container);
}, true);
*/
<div id="test"></div>
As you can see from the bindScroll() function it makes no sense right now.
Is there anyway to achieve the task?
You may pass the id into the eventListener callback through binding it to the updateContainer:
updateContainer: function(id) {
console.log('updateContainer');
var container = getMeById(id);
container.style.position = 'absolute';
container.style.width = x + 'px';
container.style.minHeight = z + 'px';
},
bindScroll: function(id) {
window.addEventListener('scroll', this.updateContainer.bind(this,id), false);
}
So one can do:
instance.bindScroll("testcontainer");
Note: x and z are not live so you may reload the values...
If you add more and more functions, your code could get difficult to manage. You could use inheritance and a constructor instead:
function instance(id){
this.el=document.querySelector(id);
}
instance.prototype={
bindScroll:function(){
window.addEventListener("scroll",this.update.bind(this),false);
return this;
},
update: function() {
var container = this.el;
container.style.position = 'absolute';
container.style.width = x + 'px';
container.style.minHeight = z + 'px';
return this;
}
};
So you could do:
var test=new instance("#test")
test.update().bindScroll();

Dynamically added children to svg-pan-zoom element do not pan/zoom, but previously added items do

I am creating an svg object with javascript, drawing a basic Sierpinski triangle, and then setting the svg object as a svg-pan-zoom. When zooming past a threshold, I try to re-draw the next level of triangles, which I can see on screen, but they do not react to zooming or panning.
I am currently trying to re-apply the svg-pan-zoom to the object after drawing the next level of triangles, but that does not seem to work.
The HTML is basically an empty body.
The JS code in question:
var width = 300;
var height = 300;
var length;
var maxDepth = 5;
var depth = 0;
var svg;
var div;
//2D array of triangles, where first index is their recursive depth at an offset
var triangles;
var zoomCount = 0;
$(document).ready(function () {
//init();
var ns = 'http://www.w3.org/2000/svg'
div = document.getElementById('drawing')
svg = document.createElementNS(ns, 'svg')
svg.setAttributeNS(null, 'id', 'svg-id')
svg.setAttributeNS(null, 'width', '100%')
svg.setAttributeNS(null, 'height', '100%')
div.appendChild(svg)
/*var rect = document.createElementNS(ns, 'rect')
rect.setAttributeNS(null, 'width', 100)
rect.setAttributeNS(null, 'height', 100)
rect.setAttributeNS(null, 'fill', '#f06')
svg.appendChild(rect)*/
init();
enableZoomPan();
});
function init() {
triangles = create2DArray(5);
//Calculate triangle line length
length = height/Math.sin(60*Math.PI/180) //Parameter conversion to radians
t = new Triangle(new Point(0, height), new Point(width, height), new Point(width/2, 0));
sketchTriangle(t);
//Recursively draw children triangles
drawSubTriangles(t, true);
attachMouseWheelListener();
}
function enableZoomPan() {
//Enable zoom/pan
var test = svgPanZoom('#svg-id', {
zoomEnabled: true,
controlIconsEnabled: false,
fit: true,
center: true,
minZoom: 0
});
}
function attachMouseWheelListener() {
if (div.addEventListener)
{
// IE9, Chrome, Safari, Opera
div.addEventListener("mousewheel", MouseWheelHandler, false);
// Firefox
div.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else
{
div.attachEvent("onmousewheel", MouseWheelHandler);
}
function MouseWheelHandler(e)
{
// cross-browser wheel delta
var e = window.event || e; // old IE support
//Delta +1 -> scrolled up
//Delta -1 -> scrolled down
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
console.log(delta);
zoomCount = zoomCount + delta;
if(zoomCount==15) {
for(var i = 0; i < triangles[0].length; i++) {
drawSubTriangles(triangles[0][i], false);
}
enableZoomPan();
}
return false;
}
}
function drawLine(p1, p2) {
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', p1.x);
line.setAttribute('y1', p1.y);
line.setAttribute('x2', p2.x);
line.setAttribute('y2', p2.y);
line.setAttribute('stroke', "black");
line.setAttribute('stroke-width', 1);
svg.appendChild(line);
}
//Recursive parameter if you want to draw recursively, or just stop after one level
function drawSubTriangles(t, recursive) {
//End condition, bounded by maximum recursion depth
if(depth == maxDepth && recursive==true) {
//Push triangle to depth collection, to track in case zooming in and redrawing
triangles[maxDepth-depth].push(t);
return;
}
depth = depth + 1;
//Sub triangle lengths are half of parent triangle
subLength = length/depth;
var midPoint1 = getCenter(t.p1, t.p2);
var midPoint2 = getCenter(t.p2, t.p3);
var midPoint3 = getCenter(t.p3, t.p1);
midTriangle = new Triangle(midPoint1, midPoint2, midPoint3);
sketchTriangle(midTriangle)
//Recursive call to continue drawing children triangles until max depth
if(recursive == true) {
drawSubTriangles(new Triangle(t.p1, midPoint1, midPoint3), true);
drawSubTriangles(new Triangle(midPoint3, midPoint2, t.p3), true);
drawSubTriangles(new Triangle(midPoint1, t.p2, midPoint2), true);
}
depth = depth -1;
}
function sketchTriangle(t) {
drawLine(t.p1, t.p2);
drawLine(t.p2, t.p3);
drawLine(t.p3, t.p1);
}
function create2DArray(rows) {
var arr = [];
for (var i=0;i<rows;i++) {
arr[i] = [];
}
return arr;
}
function getCenter(p1, p2) {
return new Point((p1.x + p2.x)/2, (p1.y + p2.y)/2);
}
function Point(x, y) {
this.x = x;
this.y = y;
}
function Triangle(p1, p2, p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
For some reason, svg-pan-zoom is wrapping all your SVG content inside a <g> element. Panning and zooming is then achieved by modifying a transform attribute associated with this element. So in effect, the first time you interact with the SVG, its structure changes from this:
<svg>
<line ...>
<line ...>
...
</svg>
to this:
<svg>
<g transform="matrix(1 0 0 1 0 0)">
<line ...>
<line ...>
...
</g>
</svg>
When you add more elements to the drawing, they are being appended to the root <svg> element. As a result, they aren't being transformed at all.
You can fix this easily enough. Just wrap your drawing inside a <g> element before invoking svg-pan-zoom. It will then use this element instead of adding its own. When adding to the drawing, append the new objects to this element.
Here's your code, with very minor modifications:
var width = 300;
var height = 300;
var length;
var maxDepth = 5;
var depth = 0;
var svg;
var svgg; /* Top <g> element inside svg */
var div;
//2D array of triangles, where first index is their recursive depth at an offset
var triangles;
var zoomCount = 0;
$(document).ready(function () {
//init();
var ns = 'http://www.w3.org/2000/svg'
div = document.getElementById('drawing')
svg = document.createElementNS(ns, 'svg')
svg.setAttributeNS(null, 'id', 'svg-id')
svg.setAttributeNS(null, 'width', '100%')
svg.setAttributeNS(null, 'height', '100%')
svgg = document.createElementNS(ns, 'g')
svg.appendChild(svgg)
div.appendChild(svg)
init();
enableZoomPan();
});
function init() {
triangles = create2DArray(5);
//Calculate triangle line length
length = height/Math.sin(60*Math.PI/180) //Parameter conversion to radians
t = new Triangle(new Point(0, height), new Point(width, height), new Point(width/2, 0));
sketchTriangle(t);
//Recursively draw children triangles
drawSubTriangles(t, true);
attachMouseWheelListener();
}
function enableZoomPan() {
//Enable zoom/pan
var test = svgPanZoom('#svg-id', {
zoomEnabled: true,
controlIconsEnabled: false,
fit: true,
center: true,
minZoom: 0
});
}
function attachMouseWheelListener() {
if (div.addEventListener)
{
// IE9, Chrome, Safari, Opera
div.addEventListener("mousewheel", MouseWheelHandler, false);
// Firefox
div.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else
{
div.attachEvent("onmousewheel", MouseWheelHandler);
}
function MouseWheelHandler(e)
{
// cross-browser wheel delta
var e = window.event || e; // old IE support
//Delta +1 -> scrolled up
//Delta -1 -> scrolled down
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
zoomCount = zoomCount + delta;
if(zoomCount==15) {
for(var i = 0; i < triangles[0].length; i++) {
drawSubTriangles(triangles[0][i], false);
}
enableZoomPan();
}
return false;
}
}
function drawLine(p1, p2) {
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', p1.x);
line.setAttribute('y1', p1.y);
line.setAttribute('x2', p2.x);
line.setAttribute('y2', p2.y);
line.setAttribute('stroke', "black");
line.setAttribute('stroke-width', 1);
svgg.appendChild(line);
}
//Recursive parameter if you want to draw recursively, or just stop after one level
function drawSubTriangles(t, recursive) {
//End condition, bounded by maximum recursion depth
if(depth == maxDepth && recursive==true) {
//Push triangle to depth collection, to track in case zooming in and redrawing
triangles[maxDepth-depth].push(t);
return;
}
depth = depth + 1;
//Sub triangle lengths are half of parent triangle
subLength = length/depth;
var midPoint1 = getCenter(t.p1, t.p2);
var midPoint2 = getCenter(t.p2, t.p3);
var midPoint3 = getCenter(t.p3, t.p1);
midTriangle = new Triangle(midPoint1, midPoint2, midPoint3);
sketchTriangle(midTriangle)
//Recursive call to continue drawing children triangles until max depth
if(recursive == true) {
drawSubTriangles(new Triangle(t.p1, midPoint1, midPoint3), true);
drawSubTriangles(new Triangle(midPoint3, midPoint2, t.p3), true);
drawSubTriangles(new Triangle(midPoint1, t.p2, midPoint2), true);
}
depth = depth -1;
}
function sketchTriangle(t) {
drawLine(t.p1, t.p2);
drawLine(t.p2, t.p3);
drawLine(t.p3, t.p1);
}
function create2DArray(rows) {
var arr = [];
for (var i=0;i<rows;i++) {
arr[i] = [];
}
return arr;
}
function getCenter(p1, p2) {
return new Point((p1.x + p2.x)/2, (p1.y + p2.y)/2);
}
function Point(x, y) {
this.x = x;
this.y = y;
}
function Triangle(p1, p2, p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ariutta.github.io/svg-pan-zoom/dist/svg-pan-zoom.js"></script>
<div id="drawing"></div>
Note: One thing I don't understand is why svg-pan-zoom doesn't just modify the SVG viewBox attribute. Then it wouldn't have to modify the document structure at all.

Performance decrease when adding KineticJS nodes to canvas

I'm working on a floorplan editor program which is implemented in part using HTML5 Canvas and KineticJS. The user can select from a couple of tools to place nodes on the canvas (rooms, hallways, staircases, etc), and can then create edges between the nodes to link them.
I'm running into a problem when placing a specific type of node on my canvas: I can add any number of most types of nodes I've got defined without any performance decrease, but as soon as I try and add more than a handful of 'room' nodes, they take longer and longer to render and the stage tap event handler which creates nodes becomes unresponsive. This issue only occurs on the iPad and not when I run the application from a desktop.
All nodes are comprised of a Kinetic Circle with a particular image to represent the type of node and some data such as x/y position, type, id, and a list of attached edges. The only difference between room nodes and other special nodes is an extra Kinetic Rect and a couple of variables to represent the room itself. When creating a new node, all the attributes are filled by the constructor function, then the node is passed to a setup function to register event handlers and a render function to render it based on its type.
I'm still fairly new with these technologies, so any advice, no matter how specific or general, will probably be helpful. I've attached what I think will be helpful snippets of code; if you need to see more or have questions about what's here please let me know.
Thank you so much for any time and effort.
=========================================================================
EDIT:
Removing the opacity attribute of the room nodes made a huge difference; the performance decrease is almost entirely negligible now. I'll post further updates if and when I work out why that's the case.
function Node(x, y, id, type, attr) {
this.x = x;
this.y = y;
this.nX = 0;
this.nY = 0;
this.type = type;
this.bbox;
this.id = id;
this.edges = {};
this.attr = {"zPos": 0,
"name": '',
"width": default_room_width,
"height": default_room_height};
this.render(x, y, node_radius);
}
Node.prototype.render = function(x, y, r){
//Create node on canvas
this.visual = null;
var _self = this;
if(this.type == "node" || this.type == "Hallway"){
this.visual = new Kinetic.Circle({
x: x,
y: y,
radius: r,
fill: '#2B64FF',
stroke: '#000000',
strokeWidth: 2,
draggable: true
});
nodeLayer.add(this.visual);
this.x = this.visual.x();
this.y = this.visual.y();
nodeLayer.draw();
this.visual.id = this.id;
this.setupNode(x, y, node_radius);
} else {
var image = new Image();
_self.visual = new Kinetic.Image({
x: x - (node_img_size / 2),
y: y - (node_img_size / 2),
image: image,
width: node_img_size,
height: node_img_size,
draggable: true
});
image.onload = function(){
_self.setupNode(x, y, node_radius);
nodeLayer.add(_self.visual);
_self.x = _self.visual.x();
_self.y = _self.visual.y();
nodeLayer.draw();
_self.visual.id = _self.id;
}
image.src = '../../img/' + this.type + 'tool.png';
var width = this.attr["width"];
var height = this.attr["height"];
if(this.type== "room") {
this.bbox = new Kinetic.Rect({
x: x,
y: y,
strokeWidth: 2,
stroke: "black",
fill: "black",
opacity: 0.5,
listening: true,
width: width,
height: height,
offset: {x:width/2, y:height/2}
});
setupRoom(this.bbox);
this.bbox.offsetX(default_room_width/2);
this.bbox.offsetY(default_room_height/2);
roomLayer.add(this.bbox);
roomLayer.draw();
}
}
}
//Bind event handlers for rooms
function setupRoom(room) {
room.on(tap, function(e) {
if(selectedRoom == this) {
selectedRoom = null;
this.setOpacity(0.5);
roomLayer.draw();
} else {
if(selectedRoom != null)
selectedRoom.setOpacity(0.5);
selectedRoom = this;
this.setOpacity(1);
roomLayer.draw();
}
});
room.on('mouseenter', function(e) {
is_hovering = true;
}).on('mouseleave', function(e) {
is_hovering = false;
});
}
Node.prototype.setupNode = function (x, y) {
var _self = this;
var c = this.visual;
c.on('mouseenter', function(e){
is_hovering = true;
}).on('mouseleave', function(e){
is_hovering = false;
});
c.on(tap, function(e){
if(is_adding_node == true && _self.type == "node" && linkerNode != _self) {
is_adding_node = false;
nodeDrag = false;
$.each(nodes, function(key, value) {
if(value.type == "node") {
value.visual.fill("#2B64FF");
}
});
nodeLayer.batchDraw();
joinNodes(linkerNode, _self);
} else {
handleNodeTap(e, _self);
}
});
c.on(dbltap, function(e){
console.log(_self.id);
if(selectedTool != "link"){
showMenuForNode(c);
}
});
//Drag event
c.on(touchstart, function(e){
nodeDrag = true;
}).on(touchmove, function(e){
var touchPos = stage.getPointerPosition();
var newX = c.x() + offsetX * -1;
var newY = c.y() + offsetY * -1;
_self.x = newX;
_self.y = newY;
if(_self.text != null) {
_self.text.x(_self.visual.x() - node_text_offset);
_self.text.y(_self.visual.y() - node_text_offset);
}
//Move room BB if set
if (_self.bbox != undefined) {
_self.bbox.x(_self.visual.x() + _self.visual.width()/2);
_self.bbox.y(_self.visual.y() + _self.visual.height()/2);
roomLayer.batchDraw();
}
//Update positions of connected edges
for(var x in _self.edges){
edges[_self.edges[x]].setPosition();
}
nodeLayer.batchDraw();
}).on(touchend, function(e){
currentNode = _self;
nodeDrag = false;
});
};

2 images animated using Javascript

From doing research and asking for help I have so far built an animation moving from left to right using the code in the JSFiddle below. This loops every 20 seconds.
http://jsfiddle.net/a9HdW/3/
However now I need a second image that moves from right to left and for this to automatically trigger straight after the first image has completed its animation.
If you could do this that would be amazing.
Thanks In Advance
<canvas id="canvas" width="1600" height="300"></canvas>
<script>
window.requestAnimFrame = (function(){
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById("canvas"),
cx = canvas.getContext("2d");
function Card(x,y){
this.x = x || -300;
this.y = y || 0;
this.width = 0;
this.height = 0;
this.img=new Image();
this.init=function(){
// this makes myCard available in the img.onload function
// otherwise "this" inside img.onload refers to the img
var self=this;
this.img.onload = function()
{
// getting width and height of the image
self.width = this.width;
self.height = this.height;
self.draw();
loop();
}
this.img.src = "f15ourbase.png";
}
this.draw = function(){
cx.drawImage(this.img, this.x, this.y);
}
}
var myCard = new Card(50,50);
myCard.init();
function loop(){
if((myCard.x + myCard.width) < canvas.width){
requestAnimFrame(loop);
} else {
setTimeout(function() {
// resetting card back to old state
myCard.x = 50;
myCard.y = 50;
// call the loop again
loop();
}, 20000);
}
cx.clearRect(0, 0, canvas.width, canvas.height);
myCard.x = myCard.x + 15;
myCard.draw();
}
This is little bit complicated, however, it boils down to formatting your Card function to understand which direction it is going to. Therefore you will need direction parameter and more complicated draw function which updates your card movement to direction it is supposed to go, like this:
// Updating own position, based on direction
if(this.direction === 1) {
this.x = this.x + this.stepSize; // we move to right
// if I am over canvas at right, I am done animating
if(this.x >= canvas.width) {
this.finishedAnimation = true;
}
} else {
this.x = this.x - this.stepSize; // we move to left
// if I am over canvas at left, I am done animating
if(this.x <= -this.width) {
this.finishedAnimation = true;
}
}
Also, because timing is important - you will need to trigger other card movement only after the first one is completed. Like this:
// We won't draw next card before previous is finished
if(!cardToRight.finishedAnimation) {
cardToRight.draw();
} else {
// Card at right is finished, we move the left card now
cardToLeft.draw();
}
To summarize my points, I made a code which has code comments to explain it's contents, go it through carefully:
// Animation frame gist
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
// Variable declarations
var canvas = document.getElementById("canvas"),
cx = canvas.getContext("2d"),
// Handlers for both of the cards
cardToRight,
cardToLeft;
/**
* Card declaration
*
*/
var Card = function(x, y, direction) {
// how many pixels we move
this.stepSize = 5;
// x and y position on canvas
this.x = x;
this.y = y;
// Copy values are used when reset is done
this.xCopy = this.x;
this.yCopy = this.y;
// handle to specify if animation finished
this.finishedAnimation = false;
// 1 means move to right, 0 means move to left
this.direction = direction;
// Image of the card
this.img = undefined;
// Image url for this card
this.imgSrc = "http://placehold.it/350x150"; // for your image: "f15ourbase.png"
// Image width
this.width = 0;
};
/**
* Initialize
*
*/
Card.prototype.init = function(callback) {
// self refers to this card
var self = this;
this.img = new Image();
// onload success callback
this.img.onload = function() {
// Setting own width
self.width = this.width;
// triggering callback on successfull load
return callback();
};
// onload failure callback
this.img.onerror = function() {
// Returning error message for the caller of this method
return callback("Loading image " + this.imgSrc + " failed!");
};
// Triggering image loading
this.img.src = this.imgSrc;
};
/**
* Draw self
*
*/
Card.prototype.draw = function() {
// Updating own position, based on direction
if(this.direction === 1) {
this.x = this.x + this.stepSize; // we move to right
// if I am over canvas at right, I am done animating
if(this.x >= canvas.width) {
this.finishedAnimation = true;
}
} else {
this.x = this.x - this.stepSize; // we move to left
// if I am over canvas at left, I am done animating
if(this.x <= -this.width) {
this.finishedAnimation = true;
}
}
// cx (context) could be also passed, now it is global
cx.drawImage(this.img, this.x, this.y);
};
/**
* Reset self
*
*/
Card.prototype.reset = function() {
// Using our copy values
this.x = this.xCopy;
this.y = this.yCopy;
// handle to specify if animation finished
this.finishedAnimation = false;
};
/**
* Main loop
*
*/
function loop() {
// Clear canvas
cx.clearRect(0, 0, canvas.width, canvas.height);
// We won't draw next card before previous is finished
// Alternatively, you could make getter for finishedAnimation
if(!cardToRight.finishedAnimation) {
cardToRight.draw();
} else {
// Card at right is finished, we move the left card now
cardToLeft.draw();
}
// If cardToLeft not yet animated, we are still pending
if(!cardToLeft.finishedAnimation) {
// Schedule next loop
// "return" makes sure that we are not executing lines below this
return requestAnimFrame(loop);
}
// Animation finished, starting again after 5 seconds
setTimeout(function() {
// Resetting cards
cardToRight.reset();
cardToLeft.reset();
// Start the loop again
loop();
}, 5000); // 5000 milliseconds = 5 seconds
};
/**
* Main program below
*
*/
// Card to right (1 denotes it's direction to right)
cardToRight = new Card(50, 50, 1);
// Card to left (0 denotes it's direction to left)
cardToLeft = new Card(1000, 50, 0);
// Initialize cardToRight & cardToLeft
// Because using only two cards, we can do a bit nesting here
cardToRight.init(function(err) {
// If error with image loading
if(err) {
return alert(err);
}
// Trying to initialize cardToLeft
cardToLeft.init(function(err) {
// If error with image loading
if(err) {
alert(err);
}
// All ok, lets do the main program
loop();
});
});
As a special note: If you wan't your cards appear outside the canvas remember to change values of below accordingly:
// Card to right (1 denotes it's direction to right)
cardToRight = new Card(50, 50, 1); // 50 <- x position of right card
// Card to left (0 denotes it's direction to left)
cardToLeft = new Card(1000, 50, 0); // 1000 <- x position of left card
Finally, here is working JsFiddle example

Categories