If I created a virtual grid 32x32 as a <div> example:
I want to fill one of the tile with a black box on click I have so far this:
var _proto = {
id:0,
x:0,
y:0
}
var objects = [];
$(".test").on("mousedown", function(e) {
var offset = $(this).offset();
var prex2 = 0, prey2 = 0;
prex2 = _proto.x = e.pageX-offset.left;
prey2 = _proto.y = e.pageY-offset.top;
_proto.id = (_objects.length)?_objects[_objects.length-1].id+1:0;
// Add to grid (not sure how to get proper cordinates)
$("<div style='display:absolute;width:32px;height:32px;background:black'></div>")
.css("top","")
.css("left","")
.appendTo("#maindiv");
});
I have the coordinates as prex2, and prey2 where the user clicked, but how do I know where to put it in the grid? I'm sure there a simple math equation but I can't figure it out.
Here's a snippet from a map editor that I was working on a few months back. It might help you grapple with your own code.
mapBlanket.addEventListener("mousedown", function(e) {
var sideWidth = document.getElementById("mapSide").offsetWidth;
var headHeight = document.getElementById("system").offsetHeight + 32;
var clickX = e.pageX - mapBlanket.offsetLeft - sideWidth + mapBlanket.parentNode.scrollLeft;
var clickY = e.pageY - mapBlanket.offsetTop - headHeight + mapBlanket.parentNode.scrollTop;
var tileX = clickX - (clickX % map.grid);
var tileY = clickY - (clickY % map.grid);
if (paintOn == 5) {
eventThis(tileX, tileY);
} else if (paintOn < 5) {
paintThis(tileX, tileY);
}
...
}
For reference, the map.grid was 32, same as yours. I just had a good bit defined in an object at the top of the file.
Related
To fully understand this note this; `when the page loads it gets the area of the image (width * height) and creates all the x,y positions for all the positions in the area.
This works fine.
When I have another area from pos x,y and with also an area (width * height) should pop the positions from the first list so it can separate the two areas.
Little bug I noticed is I get little lines that are horizontal to the selected area and they don't extend far from that. I believe the reason is instead of making a clean square inside the image every line is offseted by a pixel or two.
Here's a video of the behaviour https://youtu.be/v1b6dEmfxQw
so since there's already an all positions list this code created a clone of the array and removes the positions.
var drop_boxes = $('.drop-box');
var area_grid = [];
var image_width = $('.img-class')[0].naturalWidth;
var image_height = $('.img-class')[0].naturalHeight;
drop_boxes.each(function() {
var position = $(this).position();
var width = $(this).width();
var height = $(this).height();
var positions_clone = positions.slice(0);
//console.log(positions_clone.length);
var top_offset = parseInt((position['top'] * image_width)/img_width);
var left_offset = parseInt((position['left'] * image_height)/img_height);
position['top'] = top_offset;
position['left'] = left_offset;
var width_offset = parseInt((width * image_width)/img_width);
var height_offset = parseInt((height * image_height)/img_height);
var width_counter = 0;
var height_counter = 0;
var area = width_offset * height_offset;
console.log(position);
console.log(width_offset);
console.log(height_offset);
if (position['top'] < image_height-1 && position['left'] < image_width) {
for (counter = 0; counter < area; counter++) {
var pos = [parseInt(position['left']+width_counter), parseInt(position['top']+height_counter)];
var index = positions.findIndex(function(item) {
// return result of comparing `data` with `item`
// This simple implementation assumes that all `item`s will be Arrays.
return pos.length === item.length && item.every(function(n, i) { return n === pos[i] });
});
//console.log(pos);
if (index > -1) {
positions_clone.splice(index, 1);
}
//area_grid.push(pos);
if (width_counter == width_offset) {
width_counter = 0;
height_counter += 1;
}
if (counter%100 == 0) {
var percentage = Math.round((counter/area)*100, 2);
console.log("Percentage: "+percentage+"%" + " "+counter);
}
width_counter += 1;
}
console.log(positions_clone.length);
console.log(area_grid.length);
areas[area_counter] = {'area': area_grid, 'positions': positions_clone};
parent.find('.area').text(area_counter);
area_counter += 1;
}
any clues in fixing it will be appreciated. I've showed how it behaves after commenting out certain parts of the code in the video.
Change
var index = positions.findIndex(function(item) {
to
var index = positions_clone.findIndex(function(item) {
Because after each splice, the indices of the original positions doesn't change but you are still using those indices to splice the clone.
In my fabricjs application, I had created dynamic canvases(variable's also dynamic). Here, I need to detect particular canvas while mouse move on canvas.
Sample code,
var i = 0, canvasArray = [];
$(this).find('canvas').each(function() {
i++;
var DynamicCanvas = 'canvas_'+i;
canvasArray[DynamicCanvas] = new fabric.Canvas('canvas_'+i,{
width : '200',
height : '200'
});
});
after this, I have 4 different canvases. Last added canvas has been activated. But i need to add object on any canvas.
So that i have to activate canvas using mouse move event. How can i achieve it.? Please help me on this.
Mullainathan,
Here some quick solution using jQuery:
var canvasStr = '';
var canvasArray = [];
var fabricCanvasArray = [];
var htmlStr = '';
var canvas = null;
//generate canavases
for (var i = 0; i < 4; i++){
canvasArray.push('c' + i);
htmlStr += '<canvas id="c' + i + '" width="200" height="200"></canvas>'
}
//append canvasses to the body
$('body').append(htmlStr);
//to the fabricjs parent div elements assign id's and generate string for jQuery with div id's
for (var i in canvasArray){
fabricCanvasArray[i] = new fabric.Canvas(canvasArray[i], {
isDrawingMode: true
});
$('#' + canvasArray[i]).parent().attr('id', ('div' + canvasArray[i]));
canvasStr += '#div' + canvasArray[i];
if (i < canvasArray.length - 1){
canvasStr += ',';
}
}
//jQuery event for mouse over each div element of the fabric canvas
$(canvasStr).mouseover(function(){
for (var i in fabricCanvasArray){
if (fabricCanvasArray[i].lowerCanvasEl.id == $(this).children(':first').attr('id')){
canvas = fabricCanvasArray[i];
canvas.freeDrawingBrush.width = 10;
var r = 255 - i*50;
var g = i * 50;
var b = 200 - i * 40;
canvas.freeDrawingBrush.color = 'rgb(' + r + ',' + g + ',' + b + ')';
canvas.on('mouse:up', function() {
//do your stuff
// canvas.renderAll();
});
break;
}
}
});
Also, you can run fiddle
I'm attempting to combine a JavaScript mechanism for auto placing the users cursor inside of an input box through the mouseover and mousemove listeners.
I have an almost perfect working example here: http://codepen.io/anon/pen/doxNLm?editors=101
var current_element = document.getElementById("hover");
current_element.onmousemove = function showCoords(evt) {
var form = document.forms.form_coords;
var parent_id = this.id;
form.parentId.value = parent_id;
form.pageXCoords.value = evt.pageX;
form.pageYCoords.value = evt.pageY;
form.layerXCoords.value = evt.layerX;
form.layerYCoords.value = evt.layerY;
function getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
};
var element_base_browser_styles = window.getDefaultComputedStyle(current_element);
var total_text_pixal_length = getTextWidth(current_element.value, element_base_browser_styles.fontFamily + " " + element_base_browser_styles.fontSize);
var add_char_pixal_lengths = 0;
var myStringArray = current_element.value.split('');
var arrayLength = myStringArray.length;
for (var i = 0; i <= arrayLength; i++) {
var get_char_value = getTextWidth(myStringArray[i], element_base_browser_styles.fontFamily + " " + element_base_browser_styles.fontSize);
add_char_pixal_lengths = add_char_pixal_lengths + (get_char_value) + 1.311111111111; //every char value is added together.
// console.log("Total: " + x);
if ((add_char_pixal_lengths)> (evt.layerX)) {
this.setSelectionRange(i, i);
add_char_pixal_lengths = 0;
break;
}
}
}
current_element.onmouseover = function() {
this.focus()
}
The problem I'm having is like Geosynchronous orbit; the cursor shifts out of place sometimes a few pixels (left or right). My calculation probably sucks, but I'm not sure canvas is really the best way to do the measurement? Is there a better way?
mousemove listener to receive element cursor coordinates from e.pageX
font style using window.getComputedStyles(input_element)
arr.split('') from input_element.text string: x = ['a','b','c']
'for loop' the array, generate a canvas and measure each characters width
add all char widths one by one until the value is greater than e.pageX
set the 'for loop' iterate as the setSelectionRange(i, i)
Any help or suggestions on making this better would be appreciated. Thanks!
I wrote a little test program, exploring my problem, and it works the way I expect it, printing "four, five, six".
var foo = function() {
console.log("just one more test")
var destination = new Array;
data = [ "four", "five" , "six" ]
var parent = [ 0, 1, 2 ];
var something;
parent.forEach(function(element) {
something = data[element];
destination.push(something);
})
destination.forEach(function (thing) {
console.log(thing);
})
}
foo();
But in my real code, when I push things on to my 'clickable' array, all of the entries mutate into the current value of the 'clicker' variable. There are 3 entries in my 'scheme_list', and they draw correctly, but as I try to build areas to click on, at each iteration of the loop "in the loop" prints the value just pushed on to the array for every instance. That is, the instances of 'clicker' already in the loop change to the current value of clicker. I'm scratching my head trying to understand the difference between my real code and my test code. Or, more to the point, how to fix my real code.
var layout_color_schemes = function(scheme_list) {
var canvas = document.getElementById('color_picker_canvas');
var ctx = canvas.getContext('2d');
var x_upper_left = 5;
var y_upper_left = 5;
var width = 200;
var height = 30;
var clickables = new Array;
var clicker = {};
clicker.rect = {};
clicker.rect.width = width;
clicker.rect.height = height;
scheme_list.forEach(function(row) {
var grad = ctx.createLinearGradient(0, 0, 100, 0);
var cscheme = jQuery.parseJSON(row.json);
cscheme.forEach(function(color_point) {
grad.addColorStop(color_point[0], 'rgb(' + color_point[1] + ','
+ color_point[2] + ',' + color_point[3] + ')');
})
ctx.fillStyle = grad;
ctx.fillRect(x_upper_left, y_upper_left, width, height);
clicker.rect.x = x_upper_left;
clicker.rect.y = y_upper_left;
clicker.scheme = cscheme;
clicker.name = row.name;
clickables.push(clicker);
printf("clickables size = %d", clickables.length)
for (index = 0; index < clickables.length; ++index) {
printf("Index is %d", index)
printf("in the loop %j", clickables[index])
}
ctx.fillStyle = 'black'
ctx.fillText(row.name, x_upper_left + width + 10, 5 + y_upper_left
+ (height / 2));
y_upper_left = y_upper_left + height + 10;
});
clickables.forEach(function(area) {
printf("before call clickable area = %j", area)
});
wire_clickables(clickables);
};
function wire_clickables(clickables) {
clickables.forEach(function(area) {
if (area.hasOwnProperty('rect')) {
printf("wiring a clickable %j", area);
$("#color_picker_canvas").mousemove(function(e) {
var inside = false;
var offsetX = e.pageX - $(this).position().left;
var offsetY = e.pageY - $(this).position().top;
if (area && contains(area.rect, offsetX, offsetY)) {
document.body.style.cursor = 'pointer'
}
else {
document.body.style.cursor = 'default'
}
})
}
})
}
function contains(rect, x, y) {
return (x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y
+ rect.height)
}
The clicker object exists outside of the loop, so all you are doing is pushing the same reference onto clickables. Instead, you want to push a copy of it. There are many ways to do this, but in your case this may be one of the simplest ways:
Replace
clickables.push(clicker);
with
clickables.push(JSON.parse(JSON.stringify(clicker));
Alternatively, move the clicker declaration and initialization inside the loop.
So I'm a newbie and should obviously spend time in the tuts, but I'm looking for a quick answer. Basically, I've created a grid of movie clips with AS3. When I 'preview' the flash (as a flash or HTML) it shows up fine. Success. Yet, the stage remains empty.
Q1) Will the stage remain empty as I have used AS3 to dynamically 'draw' the grid of mc's? Or is there a slit of code I am missing to make this baby show up on the stage?
Q2) I've managed to use alpha to make the MC's 'fade' on hover - but I want to make them change color (to red) when hovered over. I've searched everywhere and can't seem to find the right script.
Here is my code:
var stage = new createjs.Stage("canvas");
var image = new createjs.Bitmap("images/square.png");
stage.addChild(image);
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
image.x += 10;
stage.update();
}
var x0:Number = 0;
var y0:Number = 0;
var nt:Number = 72;
var nc = 10;
var vd:Number = 12;
var hd:Number = 12;
for (var i = 1; i <= nt; i++) {
var mc = this.attachMovie("square", "square" + i, i);
var aprox = Math.floor((i - 1) / nc);
mc._x = x0 + hd * ((i - aprox * nc) - 1);
mc._y = y0 + aprox * vd;
mc.useHandCursor = true;
// fade in
mc.onRollOver = function()
{
this.onEnterFrame = function()
{
if (this._alpha > 0) {
this._alpha -= 10;
} else {
this._alpha = 0;
delete this.onEnterFrame;
}
};
};
// fade out
mc.onRollOut = function()
{
this.onEnterFrame = function()
{
if (this._alpha < 100) {
this._alpha += 10;
} else {
this._alpha = 100;
delete this.onEnterFrame;
}
};
};
}
Thanks in advance - sorry I am a noob.
This will never work. 1/3 of your code is in AS3, 2/3 in AS2. Considering you haven't been thrown any error, I assume you exported it as AS2.