Javascript Extensibility - javascript

I've a script, which manipulates with canvas. I call it like this:
namespace.module.do(canvas, paramString);
I'd like to move the call to the canvas itself, so it'll somewhat similar to:
<canvas namespace.module.dobehavior=paramString />
Can I do it with JS and if not how close can I get to it?

The canvas is a DOM object, so you could attach functions to it. In your example:
document.getElementsByTagName("canvas")[0].namespace.module.dobehavior = function(paramString) { ... code ... };
(obviously, document.getElementsByTagName("canvas")[0].namespace and document.getElementsByTagName("canvas")[0].namespace.module would need to be an object, so you might need to do
document.getElementsByTagName("canvas")[0].namespace = { module : { dobehavior : function(paramString) { ... } } };
And then if you had the canvas element somewhere (possibly also through var canvas = document.getElementsByTagName("canvas")[0];) you could do
canvas.namespace.module.dobehavior("someString");
Is that what you mean?

In JQuery
$(function() {
$("canvas[ns.mod.colorBehavior]") {
var color = $(this).attr("ns.mod.colorBehavior");
if (color == "red") {
var context = this.getContext('2d');
context.fillStyle = "#ff0000";
context.fillRect(0,0,width,height);
}
}
}
Where width and heigh are the width and height of your canvas element (or a higher value like 10000).

Related

svg color inside fabricjs canvas not changing

i'm trying to change svg path's fill which is inside fabricjs canvas.
using this function
function changeColor(material) {
console.log(svgGroup[0].fill)
console.log(material);
if (material == 'base') {
svgGroup[0].fill = '#000000';
console.log(svgGroup[0].fill)
}
texture.needsUpdate = true;
object.children[0].material = textureMaterial;
canvas.renderAll();
}
but it doesn't updated automatically
anyone have any idea why? any thought would be helpful
i found the solution, the problem iwas i didn't set the color correctly. instead of doing this
svgGroup[0].fill = '#000000';
it should've use this
svgGroup._objects.forEach(obj => {
if (obj.id == material) {
obj.set('fill', color);
}
});
that way it is rendered when renderAll() is called

Intercept calls to HTML5 canvas element

I have a WEB application, that renders it's entire User Interface in an HTML5 canvas.
Note that I can't change the current application.
Currently, this application is being tested using Selenium.
This is done by simulating a click event at a given location in the browser window.
After the click has been executed, a sleep of 2 seconds is being performed to ensure that the entire UI is ready before moving to the next step.
Due to all the 'wait' statements, testing the application is very slow.
Therefore, I thought it was an idea to intercept all calls to the HTML5 canvas.
That way I can rely on the triggered events to know if the UI is ready to move to the next step.
Assume that I have the following code in my application that renders the canvas.
var canvas = document.getElementById("canvasElement");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 100);
Is there a way to intercept the 'fillRect' event?
I tought something along the lines:
var canvasProxy = document.getElementById("canvasElement");
canvasProxy.addEventListener("getContext", function(event) {
console.log("Hello");
});
var canvas = document.getElementById("canvasElement");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 100);
Unforuntately this is not working.
I've created a JSFiddle to play with the example.
https://jsfiddle.net/5cknym74/4/
Amy toughts?
I played a bit around with the JS API and it seems that the following might be working:
// SECTION: Store a reference to all the HTML5 'canvas' element methods.
HTMLCanvasElement.prototype._captureStream = HTMLCanvasElement.prototype.captureStream;
HTMLCanvasElement.prototype._getContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype._toDataURL = HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype._toBlob = HTMLCanvasElement.prototype.toBlob;
HTMLCanvasElement.prototype._transferControlToOffscreen = HTMLCanvasElement.prototype.transferControlToOffscreen;
HTMLCanvasElement.prototype._mozGetAsFile = HTMLCanvasElement.prototype.mozGetAsFile;
// SECTION: Patch the HTML5 'canvas' element methods.
HTMLCanvasElement.prototype.captureStream = function(frameRate) {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.captureStream');
return this._captureStream(frameRate);
}
HTMLCanvasElement.prototype.getContext = function(contextType, contextAttributes) {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.getContext');
console.log('PROPERTIES:');
console.log(' contextType: ' + contextType);
return this._getContext(contextType, contextAttributes);
}
HTMLCanvasElement.prototype.toDataURL = function(type, encoderOptions) {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.toDataURL');
return this._toDataURL(type, encoderOptions);
}
HTMLCanvasElement.prototype.toBlob = function(callback, mimeType, qualityArgument) {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.toBlob');
return this._toBlob(callback, mimeType, qualityArgument);
}
HTMLCanvasElement.prototype.transferControlToOffscreen = function() {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.transferControlToOffscreen');
return this._transferControlToOffscreen();
}
HTMLCanvasElement.prototype.mozGetAsFile = function(name, type) {
console.log('INTERCEPTING: HTMLCanvasElement.prototype.mozGetAsFile');
return this._mozGetAsFile(name, type);
}
Now that I can intercept the calls, I can find out which calls are responsible that draw a button and react accordingly.

Scaling HTML5 Canvas Image

Building a web page on which I am trying to set an image as the background of the main canvas. The actual image is 1600x805 and I am trying to code the application so that it will scale the image either up or down, according to the dimensions of the user's screen. In Prime.js I have an object that sets the properties of the application's canvas element located in index.html. Here is the code for that object:
function Prime(w,h){
if(!(function(){
return Modernizr.canvas;
})){ alert('Error'); return false; };
this.context = null;
this.self = this;
this.globalCanvasMain.w = w;
this.globalCanvasMain.h = h;
this.globalCanvasMain.set(this.self);
this.background.setBg();
}
Prime.prototype = {
constructor: Prime,
self: this,
globalCanvasMain: {
x: 0,
y: 0,
set: function(ref){
ref.context = document.getElementById('mainCanvas').getContext('2d');
$("#mainCanvas").parent().css('position', 'relative');
$("#mainCanvas").css({left: this.x, top: this.y, position: 'absolute'});
$("#mainCanvas").width(this.w).height(this.h);
}
},
background: {
bg: null,
setBg: function(){
this.bg = new Image();
this.bg.src = 'res/background.jpg';
}
},
drawAll: function(){
this.context.drawImage(this.background.bg, 0,0, this.background.bg.width,this.background.bg.height,
this.globalCanvasMain.x,this.globalCanvasMain.y, this.globalCanvasMain.w,this.globalCanvasMain.h);
}
};
The primary interface through which external objects like this one will interact with the elements in index.html is home.js. Here's what happens there:
$(document).ready(function(){
var prime = new Prime(window.innerWidth,window.innerHeight);
setInterval(prime.drawAll(), 25);
});
For some reason, my call to the context's drawImage function clips only the top left corner from the image and scales it up to the size of the user's screen. Why can I not see the rest of the image?
The problem is that the image has probably not finished loading by the time you call setInterval. If the image is not properly loaded and decoded then drawImage will abort its operation:
If the image isn't yet fully decoded, then nothing is drawn
You need to make sure the image has loaded before attempting to draw it. Do this using the image's onload handler. This operation is asynchronous so it means you also need to deal with either a callback (or a promise):
In the background object you need to supply a callback for the image loading, for example:
...
background: {
bg: null,
setBg: function(callback) {
this.bg = new Image();
this.bg.onload = callback; // supply onload handler before src
this.bg.src = 'res/background.jpg';
}
},
...
Now when the background is set wait for the callback before continue to drawAll() (though, you never seem to set a background which means drawImage tries to draw null):
$(document).ready(function(){
var prime = new Prime(window.innerWidth, window.innerHeight);
// supply a callback function reference:
prime.background.setBg(callbackImageSet);
// image has loaded, now you can draw the background:
function callbackImageSet() {
setInterval(function() {
prime.drawAll();
}, 25);
};
If you want to draw the complete image scaled to fit the canvas you can simplify the call, just supply the new size (and this.globalCanvasMain.x/y doesn't seem to be defined? ):
drawAll: function(){
this.context.drawImage(this.background.bg, 0,0,
this.globalCanvasMain.w,
this.globalCanvasMain.h);
}
I would recommend you to use requestAnimationFrame to draw the image as this will sync with the monitor update.
Also remember to provide callbacks for onerror/onabort on the image object.
There is a problem with the setInterval function. You are not providing proper function reference. The code
setInterval(prime.drawAll(), 25);
execute prime.drawAll only once, and as the result only little part of the image which is being loaded at this moment, is rendered.
Correct code should be:
$(document).ready(function(){
var prime = new Prime(window.innerWidth, window.innerHeight);
setInterval(function() {
prime.drawAll();
}, 25);
});

Variable values aren't available for use after image.onload?

I'm using Canvas to perform a couple of things on an image which is loaded/drawn using image.onload & context.drawImage combo. I'm calculating the bounding size for scaling the images using a simple function which returns the values. I need those values for use at a later point in my code, but no matter what I do, I'm not able to assign the values to a variable. I'm also not able to access my Canvas's styleheight/stylewidth attributes after I assign it the calculated dimensions.
Here's a pseudos ample of my code
$(document).ready(function(){
//Canvas access, context reference etc here.
//Since I'm assigning styles to the canvas on the fly, the canvas has no ht/wdt yet
var dimes = '';
var image = new Image();
image.onload = function(){
//Apply original image height/width as canvas height/width 'attributes'
//(so that I can save the original sized image)
//Check if the image is larger than the parent container
//Calculate bounds if not
//Apply calculated dimensions as 'style' height/width to the canvas, so that the image fits
dimes = scaleImage(...);
//Works!
console.log(dimes);
//Rest all code
}
image.src = '...';
//Blank!!!
console.log(dimes);
//These all blank as well!!!
jQuery('#mycanvas').height() / width() / css('height') / css('width');
document.getElementById(canvas).style.height / .style.width / height / width;
});
I need to access the calculated dimensions for a 'reset' kind of function, that resets my canvas with the drawn image to the calculated size.
As #apsillers noted, the console.log(dimes) code is being executed after you simply define the image.onload() event handler.
If you want to access dimes outside of image.onload(), you'll need to ensure it's being executed after the image loads... e.g. as a response to a button click.
Put the var dimes = ""; before the $(document).ready() to make it a global variable.
Then if you need to access dimes in an event handler, it's ready for you:
$(document).ready(function() {
var image = new Image();
var dimes = "";
image.onload = function() {
dimes = scaleImage(...);
};
$(button).click(function() {
if (dimes === "") {
// image is not yet loaded
} else {
console.log(dimes);
}
});
});
Of course, dimes will now only be accessible inside this first $(document).ready() event handler. If you add another one (which you can certainly do in jQuery), you'll need to use the $.fn.data() jQuery object method to store dimes:
$(document).ready(function() {
var image;
$(document).data("dimes", ""); // initializes it
image.onload = function() {
$(document).data("dimes", scaleImage(...));
};
});
// some other code
$(document).ready(function() {
$("#myButton").click(function() {
var dimes = $(document).data("dimes");
if (dimes === "") {
// image not yet loaded
} else {
console.log(dimes);
}
});
});
Your img.onload function can run only after the JavaScript execution thread stops being busy, i.e., after your ready function completes. Thus, your console.log(dimes) call is running before your onload function.
Put any code that needs to use dimes inside of the onload function. Otherwise, the code the needs to use dimes might run before the onload handler fires.
http://jsfiddle.net/KxTny/1/
$(document).ready(function(){
var dimes = 0;
var width = 20;
var height = 30;
pass(dimes, width, height);
});​
function pass(dimes, width, height) {
alert(dimes);
alert(height);
alert(width);
}

How to implement drag and drop for HTML5 Canvas painting application?

Based on Creating an HTML 5 canvas painting application I created a HTML5 canvas painting application. It works fine, but after creating each object I just need to drag the objects.
Working demo
How to implement drag and drop of the figures?
When the user clicks on the canvas, you have to check the coordinates (compare it to the coordinates for the objects), and see if it's on an object. E.g. You can test if a point (e.g. the coordinates for the mousedown even) is within a circle with this method:
function (pt) {
return Math.pow(pt.x - point.x,2) + Math.pow(pt.y - point.y,2) <
Math.pow(radius,2);
};
If the mousedown is on the object, you have to change the objects coordinates according to how the mouse is moved.
Here is an example, where you can drag a circle:
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
drawCircle(circle);
element = document.getElementById('canvas');
element.addEventListener('mousedown', startDragging, false);
element.addEventListener('mousemove', drag, false);
element.addEventListener('mouseup', stopDragging, false);
element.addEventListener('mouseout', stopDragging, false);
}
function mouseX(e) {
return e.clientX - element.offsetLeft;
}
function mouseY(e) {
return e.clientY - element.offsetTop;
}
var Point = function (x, y) {
this.x = x;
this.y = y;
return this;
}
var Circle = function (point, radius) {
this.point = point;
this.radius = radius;
this.isInside = function (pt) {
return Math.pow(pt.x - point.x, 2) + Math.pow(pt.y - point.y, 2) <
Math.pow(radius, 2);
};
return this;
}
function startDragging(e) {
var p = new Point(e.offsetX, e.offsetY);
if(circle.isInside(p)) {
deltaCenter = new Point(p.x - circle.point.x, p.y - circle.point.y);
}
}
function drag(e) {
if(deltaCenter != null) {
circle.point.x = (mouseX(e) - deltaCenter.x);
circle.point.y = (mouseY(e) - deltaCenter.y);
drawCircle(circle);
}
}
function stopDragging(e) {
deltaCenter = null;
}
function drawCircle(circle) {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(circle.point.x, circle.point.y, circle.radius, 0, Math.PI*2, true);
ctx.fill();
}
var circle = new Circle(new Point(30, 40), 25);
var deltaCenter = null;
var element;
</script>
</head>
<body>
<canvas id="canvas" width="400" height="300"></canvas>
</body>
</html>
Try it on jsFiddle
The same effect can be accomplished using Raphael.js (http://raphaeljs.com/) with Joint.jS (http://www.jointjs.com/).
Shapes created with Raphael can be accessed like any DOM element and can be manipulated via attributes. It is an awesome framework.
Joint.js helps in connecting the shapes. They also have a diagramming library and can help create ERD, Statemachine and several common diagrams. The best part is that you can extend their diagram element and create your own custom elements. Its jaw-dropingly cool.
Checkout their demos with source code at http://www.jointjs.com/demos
If you are using the raphael as "raw" lib you must handle the undo/redo by yourself.
The graphiti lib did have Undo/Redo Stack inside and supports the export for SVG, PNG, JSON,...
Additional you have some kind of Viso like connectors and ports.
http://www.draw2d.org/graphiti/jsdoc/#!/example
Greetings
I don't think there's an easy way to do this.
If you're just dealing with lines, my approach would be to keep track of all lines created, with starting coordinates, ending coordinates and some kind of z-index. When the user starts a dragging action (onmousedown), you have to check if the point is near the line, and then update the object and redraw the canvas when the mouse is moved.
How can I tell if a point belongs to a certain line?
This gets a lot more complicated if you're dealing with complex objects though. You'll probably have to find a solution to check if a point is inside a path.
Objects drawn into HTML5 Canvas are turned into pixels and then forgotten. You can't adjust properties on them and have the canvas update to see the effects. You can remember them yourself, but the canvas will still have those pixels set, so you'd have to basically redraw the whole canvas (or at least some of it) when you adjust a property.
You might want to consider SVG for this application instead, SVG elements are remembered in the DOM and when their properties are updated the browser will update the graphic to reflect the changes.
If you must use canvas, then you're going to need to write quite a bit of code to handle mouse-hits, object properties, and repaints.

Categories

Resources