I want to replicate the basic functionality of a free transform tool (no rotation), by dragging on the border of a easeljs Shape and adjusting the container to match it. I'm currently using the scaleX and scaleY properties and it sort of works but is not quite right.
If you do one scaling transformation it works pretty well. However if you release, then do another scaling transformation, it jumps very glitchily, and can occasionally break sending the x/y coordinates all the way to stage 0. Any help on this issue would be great!
http://jsfiddle.net/frozensoviet/dsczvrpw/13/
//circle
var circle = new createjs.Shape(new createjs.Graphics()
.beginFill("#b2ffb2")
.drawCircle(0, 0, 50));
circle.setBounds(0, 0, 50, 50);
//create the border as a seperate object
var cBorder = new createjs.Shape(new createjs.Graphics().setStrokeStyle(10)
.beginStroke("#000").drawCircle(0, 0, 50));
cBorder.setBounds(0, 0, 50, 50);
//add both to the container
circleContainer.addChild(circle);
circleContainer.addChild(cBorder);
var cWidth = circleContainer.getBounds().width;
var cHeight = circleContainer.getBounds().height;
//find initial mouse position relative to circle center
cBorder.on("mousedown", function (evt) {
//initial mouse pos
this.initial = {
x: Math.abs(-(circleContainer.x - evt.stageX)),
y: Math.abs(circleContainer.y - evt.stageY)
};
});
//set the relevant circle axis scale to ratio of mouse pos/initial mouse pos
cBorder.on("pressmove", function (evt) {
//current moouse pos
this.offset = {
x: Math.abs(-(circleContainer.x - evt.stageX)),
y: Math.abs(circleContainer.y - evt.stageY)
};
if (this.initial.x > this.initial.y) {
//sides
circleContainer.scaleX = this.offset.x / this.initial.x;
} else if (this.initial.x < this.initial.y) {
//top/bottom
circleContainer.scaleY = this.offset.y / this.initial.y;
} else {
//diagonals
circleContainer.scaleX = this.offset.x / this.initial.x;
circleContainer.scaleY = this.offset.y / this.initial.y;
}
stage.update();
});
The issue is your initial calculations don't account for the change in the scale of the circle. You would have to transform the coordinates using localToGlobal. Fortunately, there is an even easier way:
this.initial = {
x: Math.abs(evt.localX),
y: Math.abs(evt.localY)
};
You can also turn on ignoreScale on the border, which makes it not stretch:
createjs.Graphics().setStrokeStyle(10,null,null,null,true) // The 5th argument
Lastly, your bounds setting might work for your demo, but it is not correct. Your circle draws from the center, so it should be:
cBorder.setBounds(-25, -25, 50, 50);
Here is an updated fiddle: http://jsfiddle.net/tfy1sjnj/3/
Related
I am taking a course online and I can't find help if am stuck..... I am using brackets and p5.js
these are the instructions i have:
Edit the spotlight object by creating x and y properties initialised to your location. Also endX and endY properties initialised to one of the Minsky's location.
Assign the other 2 spotlights and create the required properties.
Make the spotlight move perfectly from you towards the Minskys by adjusting the increments of x and y properties.
If you get everything correct then it will stop over the target.
Adjust x and y properties using
"+=" or "+"
"-=" or "-"
*/
(the minsky brothers are the targets i need the spotlight to be on, the "your location" is the start location)
i will copy and paste my code and the message i get when i submit :
// other variables, you don't need to change these
var img, spotlight_image;
var spotlight1;
var spotlight2;
var spotlight3;
function preload()
{
img = loadImage('scene.png');
spotlight_image = loadImage('spotlight.png')
}
function setup()
{
createCanvas(img.width, img.height);
//complete the initialisation of the first spotlight
//with properties x, y, endX and endY
spotlight1 = {
image: spotlight_image
x: 164,
y: 810,
endX: 780,
endY: 640,
}
//Initialize the second and third spotlights
spotlight2 = {
image: spotlight_image
x: 164,
y: 810,
endX: 480,
endY: 474,
}
spotlight3 = {
image: spotlight_image
x: 164,
y: 810,
endX:766,
endY: 290,
}
}
function draw()
{
image(img, 0, 0);
// alter the properties x and y of the objects below to animate the spotlights
spotlight.x += 1;
spotlight.y += 1;
////////// DO NOT CHANGE ANYTHING BELOW /////////////
var spotlights = [spotlight1, spotlight2, spotlight3];
var spotlightSize = 300;
blendMode(BLEND);
background(30);
for (var i = 0; i < spotlights.length; i++)
{
var spotlight = spotlights[i];
//stop the spotlight if it's near enough to endx and endy
if(spotlight)
{
//stop the spotlight if it goes off of the screen
spotlight.x = min(spotlight.x, 960);
spotlight.y = min(spotlight.y, 945);
spotlight.x = max(spotlight.x, 0);
spotlight.y = max(spotlight.y, 0);
if (abs(spotlight.endX - spotlight.x) < 50
&& abs(spotlight.endY - spotlight.y) < 50)
{
spotlight.x = spotlight.endX;
spotlight.y = spotlight.endY;
}
image(spotlight.image, spotlight.x-spotlightSize/2,
spotlight.y-spotlightSize/2, spotlightSize, spotlightSize);
}
}
blendMode(DARKEST);
image(img, 0, 0);
////////// DONOT CHANGE ANYTHING ABOVE /////////////
}
the message i get when submitting:
Error in compile
SyntaxError: Unexpected identifier
Blockquote
This is fairly easy to do. If I understand correctly, you want to move an object towards a point over a certain amount of time. All you have to do is get the range between the two X coordinates and the two Y coordinates, divide them by how many frames you want it to be moving for, and update its position by that amount every frame until it reaches its destination.
I need to draw customized rectangle - the one with 4 "ears" in each corner.
So I defined my own class based on fabric.Object like this:
var CustomRect = fabric.util.createClass(fabric.Object, {
...
}
Important note: when creating objects based on my class CustomRect I want to define width and height as a size of a rectangle without those "ears".
But I have a problem. I can not draw outside of an area defined by width x height.
Everything else gets clipped - it's drawn but not visible. So I'm not able to draw those "ears" while they go beyond the limits of an area width x height.
How to tell fabric to extend drawing area? How can I draw outside of width x height area?
Many thanks guys!
So I have found this solution. Not perfect but it works.
While Fabric adjusts the size of painting area for an object according to it's width and height parameters, I had to make my own width and height parameters.
Fabric's width and height are set to the size of painting area, while my width and height are set to the real size of a rectangle (rectangle without "ears").
Here we go, class definition first:
var CustomRect = fabric.util.createClass(fabric.Object, {
initialize: function(options) {
options || (options = { });
if (options.width || options.height){
alert('Do not use width/height, use my_width/my_height instead.');
}
// here we set our Object's width, height to create painting area for it
// It must be little larger than rectangle itself to paint "ears"
options.width = options.my_width + SIZE_EXTEND;
options.height = options.my_height + SIZE_EXTEND;
this.callSuper('initialize', options);
},
_render: function(ctx) {
var PIx2 = 6.28319; // 2 * PI
var w_half = (this.width - SIZE_EXTEND) / 2;
var h_half = (this.height - SIZE_EXTEND) / 2;
ctx.rect(this.left, this.top, this.width - SIZE_EXTEND, this.height - SIZE_EXTEND);
ctx.fill();
// "ears"
ctx.beginPath();
ctx.arc(-w_half, -h_half, 4, 0, PIx2, false);
ctx.fill();
ctx.beginPath();
ctx.arc(w_half, -h_half, 4, 0, PIx2, false);
ctx.fill();
ctx.beginPath();
ctx.arc(-w_half, h_half, 4, 0, PIx2, false);
ctx.fill();
ctx.beginPath();
ctx.arc(w_half, h_half, 4, 0, PIx2, false);
ctx.fill();
}
}
SIZE_EXTEND is a constant defined elsewhere (for my application constant is OK).
And now how I use it in my application. Adding a new rectangle onto my canvas:
var TheCanvas;
TheCanvas = new fabric.Canvas('mainCanvas');
TheCanvas.setWidth(window.innerWidth);
TheCanvas.setHeight(window.innerHeight);
TheCanvas.add(new CustomRect({
left: 500,
top: 200,
my_width: 100, // here I define size WITHOUT "ears"
my_height: 100
}));
I am trying to do something like paint with KineticJS. I am trying to draw the color with circles that originate from the mouse position. However the eventlistener of the mouse position seems too slow and when I move the mouse too fast the circles drawn are far from each other resulting this:
I have seen people filling array with points drawing lines between them, but I thought thats very bad for optimization because after dubbing the screen too much the canvas starts lagging because it has too much lines that it redraws every frame. I decided to cancel the cleaning of the layer and I am adding new circle at the current mouse position and I remove the old one for optimization. However since Im not drawing lines on fast mouse movement it leaves huge gaps. I would be very grateful if anyone can help me with this.
Here is my code:
(function() {
var stage = new Kinetic.Stage({
container: 'main-drawing-window',
width: 920,
height: 750
}),
workplace = document.getElementById('main-drawing-window'),
layer = new Kinetic.Layer({
clearBeforeDraw: false
}),
border = new Kinetic.Rect({
stroke: "black",
strokeWidth: 2,
x: 0,
y: 0,
width: stage.getWidth(),
height: stage.getHeight()
}),
brush = new Kinetic.Circle({
radius: 20,
fill: 'red',
strokeWidth: 2,
x: 100,
y: 300
});
Input = function() {
this.mouseIsDown = false;
this.mouseX = 0;
this.mouseY = 0;
this.offsetX = 0;
this.offsetY = 0;
};
var input = new Input();
document.documentElement.onmousedown = function(ev) {
input.mouseIsDown = true;
};
document.documentElement.onmouseup = function(ev) {
input.mouseIsDown = false;
};
document.documentElement.onmousemove = function(ev) {
ev = ev || window.event;
// input.mouseX = (ev.clientX - workplace.offsetLeft);
// input.mouseY = (ev.clientY - workplace.offsetTop);
input.mouseX = (ev.offsetX);
input.mouseY = (ev.offsetY);
};
function DistanceBetweenPoints(x1, y1, x2, y2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
}
var canvasDraw = setInterval(function() {
// console.log(input);
if (input.mouseIsDown) {
workplace.style.cursor = "crosshair";
var currentBrushPosition = brush.clone();
currentBrushPosition.setX(input.mouseX);
currentBrushPosition.setY(input.mouseY);
// var distance = DistanceBetweenPoints(brush.getX(), brush.getY(), currentBrushPosition.getX(), currentBrushPosition.getY());
// if (distance > brush.getRadius() * 2) {
// var fillingLine = new Kinetic.Line({
// points: [brush.getX(), brush.getY(), currentBrushPosition.getX(), currentBrushPosition.getY()],
// stroke: 'yellow',
// strokeWidth: brush.getRadius()*2,
// lineJoin: 'round'
// });
// // layer.add(fillingLine);
// }
layer.add(currentBrushPosition);
brush.remove();
brush = currentBrushPosition;
layer.draw();
// if (fillingLine) {
// fillingLine.remove();
// }
}
if (!input.mouseIsDown) {
workplace.style.cursor = 'default';
}
}, 16);
layer.add(border);
stage.add(layer);
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Coloring Game</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/kineticjs/5.2.0/kinetic.min.js"></script>
</head>
<body>
<div id="main-drawing-window"></div>
<script type="text/javascript" src="./JS files/canvas-draw.js"></script>
</body>
</html>
Don't use individual Kinetic.Circles for each mousemove. Every Kinetic object is a "managed" object and that management takes up a lot of resources. KineticJS will slow to a crawl as the number of circles increases with every mousemove.
Instead, use a Kinetic.Shape and draw you circles onto the canvas with
// This is Pseudo-code since I haven't worked with KineticJS in a while
shapeContext.beginPath();
shapeContext.arc(mouseX,mouseY,20,0,Math.PI*2);
shapeContext.fillStrokeShape(this);
This will probably clear your problem, but if the mouse is moved very far in a single mousemove then you might have to draw a lineTo (instead of arc) between the last mouse point and the current far-away mouse point.
I have a very ordinary rectangle created in Paper.js and I'd like to resize it, but I can't find any obvious ways to do it.
var rect = new Rectangle([0, 0],[width,height]);
rect.center = mousePoint;
var path = new Path.Rectangle(rect, 4);
path.fillColor = fillColor;
path.meta = fillColor;
There's a scale transformation method, but it's not really for mouse interaction and my goal is to create a handle that can resize a component.
Note that PaperJS has three different kinds of Rectangles:
Rectangle — This is the basic type (data structure) that defines a rectangle. Basically, top-left point, width, and height. (Nothing is displayed on the screen.) This kind of rectangle can be resized by setting its size property, for instance:
let rect;
const originalSize = [50, 50];
const newSize = [100, 100];
rect = new Rectangle([10, 50], originalSize);
rect.size = newSize;
Path.Rectangle — This is a method for generating a list of Segments that make up a rectangular-shaped Path. This does get displayed, but a Path lacks methods associated with a rectangle. For instance, a Path.Rectangle has no size property (so trying to modify it has no effect). To resize a Path you can use the scale() method as another answer proposes, or modify its Segments:
rect = new Path.Rectangle([210, 50], originalSize);
rect.strokeColor = "red";
rect.strokeWidth = 3;
rect.segments[0].point = rect.segments[0].point.add([-25, 25]); // lower left point
rect.segments[1].point = rect.segments[1].point.add([-25, -25]); // upper left point
rect.segments[2].point = rect.segments[2].point.add([25, -25]); // upper right point
rect.segments[3].point = rect.segments[3].point.add([25, 25]); // lower right point
Shape.Rectangle — This kind of rectangle gets displayed and exposes properties about its shape, such as size. To resize a Shape.Rectangle you can modify its size property directly:
rect = new Shape.Rectangle([410, 50], originalSize)
rect.strokeColor = "blue"
rect.strokeWidth = 3
rect.size = newSize
Most likely, if you want to draw a rectangle and modify its properties after the fact, the rectangle you are looking for is Shape.Rectangle.
Here is a Sketch that lets you play around with the different kinds of rectangles.
You can calculate the scaling by dividing the intended width/height of your rectangle with the current width/height of your rectangle.
Then you can use that scaling 'coefficient' to apply the scaling.
Based on your code above, you can get the current width/height of your rectangle by using: rect.bounds.width and rect.bounds.height
Here's a function you can use
var rectangle = new Shape.Rectangle({
from: [0, 0],
to: [100, 50],
fillColor: 'red'
});
function resizeDimensions(elem,width,height){
//calc scale coefficients and store current position
var scaleX = width/elem.bounds.width;
var scaleY = height/elem.bounds.height;
var prevPos = new Point(elem.bounds.x,elem.bounds.y);
//apply calc scaling
elem.scale(scaleX,scaleY);
//reposition the elem to previous pos(scaling moves the elem so we reset it's position);
var newPos = prevPos + new Point(elem.bounds.width/2,elem.bounds.height/2);
elem.position = newPos;
}
resizeDimensions(rectangle,300,200)
And here's the Sketch for it.
Be aware that the above function will also reposition the element at it's previous position but it will use top-left positioning. Paper.js uses the element's center to position them so I'm clarifying this so it doesn't cause confusion
I'm trying to create an array of shapes that overlap. But I'm having difficulty preventing those shapes stacking on top of one-another.
I guess I want them to mesh together, if that makes sense?
Here's the code:
var overlap_canvas = document.getElementById("overlap");
var overlap_context = overlap_canvas.getContext("2d");
var x = 200;
var y = x;
var rectQTY = 4 // Number of rectangles
overlap_context.translate(x,y);
for (j=0;j<rectQTY;j++){ // Repeat for the number of rectangles
// Draw a rectangle
overlap_context.beginPath();
overlap_context.rect(-90, -100, 180, 80);
overlap_context.fillStyle = 'yellow';
overlap_context.fill();
overlap_context.lineWidth = 7;
overlap_context.strokeStyle = 'blue';
overlap_context.stroke();
// Degrees to rotate for next position
overlap_context.rotate((Math.PI/180)*360/rectQTY);
}
And here's my jsFiddle:
http://jsfiddle.net/Q8yjP/
And here's what I'm trying to achieve:
Any help or guidance would be greatly appreciated!
You cannot specify this behavior but you can implement an algorithmic-ish approach that uses composite modes.
As shown in this demo the result will be like this:
Define line width and the rectangles you want to draw (you can fill this array with the loop you already got to calculate the positions/angles - for simplicity I just use hard-coded ones here):
var lw = 4,
rects = [
[20, 15, 200, 75],
[150, 20, 75, 200],
[20, 150, 200, 75],
[15, 20, 75, 200]
], ...
I'll explain the line width below.
/// set line-width to half the size
ctx.lineWidth = lw * 0.5;
In the loop you add one criteria for the first draw which is also where you change composite mode. We also clear the canvas with the last rectangle:
/// loop through the array with rectangles
for(;r = rects[i]; i++) {
ctx.beginPath();
ctx.rect(r[0], r[1], r[2], r[3]);
ctx.fill();
ctx.stroke();
/// if first we do a clear with last rectangle and
/// then change composite mode and line width
if (i === 0) {
r = rects[rects.length - 1];
ctx.clearRect(r[0] - lw * 0.5, r[1] - lw * 0.5, r[2] + lw, r[3] + lw);
ctx.lineWidth = lw;
ctx.globalCompositeOperation = 'destination-over';
}
}
This will draw the rectangles and you have the flexibility to change the sizes without needing to recalculate clipping.
The line-width is set separately as stroke strokes the line from the middle. Therefor, since we later use destination-over mode it means half of the line won't be visible as we first fill which becomes part of destination so that the stroke will only be able to fill outside the stroked area (you could reverse the order of stroke and fill but will always run into an adjustment for the first rectangle).
We also need it to calculate the clipping which must include (half) the line on the outside.
This is also why we initially set it to half as the whole line will be drawn the first time - otherwise the first rectangle will have double as thick borders.
The only way to do it to cut your rectangles and compute which sub rectangle goes over which one. But I think you will have to draw your borders and inner rectangles separately because separating rectangles will add additional borders.
Hope it helped
Sadly, the feature you want of setting z-indexes on part of an element using canvas is not available currently. If you just need it for the four rectangle object you could do something like this which hides part of the rectangle to fake the effect you want, however this is hard coded to only 4 rectangles.
var overlap_canvas = document.getElementById("overlap");
var overlap_context = overlap_canvas.getContext("2d");
var x = 200;
var y = x;
var rectQTY = 4 // Number of rectangles
overlap_context.translate(x, y);
for (j = 0; j < rectQTY; j++) { // Repeat for the number of rectangles
// Draw a rectangle
overlap_context.beginPath();
overlap_context.rect(-90, -100, 180, 80);
overlap_context.fillStyle = 'yellow';
overlap_context.fill();
overlap_context.lineWidth = 7;
overlap_context.strokeStyle = 'blue';
overlap_context.stroke();
if (j === 3) {
overlap_context.beginPath();
overlap_context.rect(24, -86, 72, 80);
overlap_context.fillStyle = 'yellow';
overlap_context.fill();
overlap_context.closePath();
overlap_context.beginPath();
overlap_context.moveTo(20, -89.5);
overlap_context.lineTo(100, -89.5);
overlap_context.stroke();
overlap_context.closePath();
overlap_context.beginPath();
overlap_context.moveTo(20.5, -93.1);
overlap_context.lineTo(20.5, 23);
overlap_context.stroke();
overlap_context.closePath();
}
// Degrees to rotate for next position
overlap_context.rotate((Math.PI / 180) * 360 / rectQTY);
}
Demo here
If you have to make it dynamic, you could cut the shapes like Dark Duck suggested or you could try to create a function that detects when an object is overlapped and redraw it one time per rectangle (hard to do and not sure if it'd work). Perhaps you could come up with some equation for positioning the elements in relation to how I have them hard coded now to always work depending on the rotation angle, this would be your best bet IMO, but I don't know how to make that happen exactly
Overall you can't really do what you're looking for at this point in time
Using pure JavaScript ...
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas id="mycanvas" width="400px" height="400px"></canvas>
<script>
window.onload = function(){
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
//cheat - use a hidden canvas
var hidden = document.createElement('canvas');
hidden.width = 400;
hidden.height = 400;
var hiddenCtx = hidden.getContext('2d');
hiddenCtx.strokeStyle = 'blue';
hiddenCtx.fillStyle = 'yellow';
hiddenCtx.lineWidth = 5;
//translate origin to centre of hidden canvas, and draw 3/4 of the image
hiddenCtx.translate(200,200);
for(var i=0; i<3; i++){
hiddenCtx.fillRect(-170, -150, 300, 120);
hiddenCtx.strokeRect(-170, -150, 300, 120);
hiddenCtx.rotate(90*(Math.PI/180));
}
//reset the hidden canvas to original status
hiddenCtx.rotate(90*(Math.PI/180));
hiddenCtx.translate(-200,-200);
//translate to middle of visible canvas
ctx.translate(200, 200);
//repeat trick, this time copying from hidden to visible canvas
ctx.drawImage(hidden, 200, 0, 200, 400, 0, -200, 200, 400);
ctx.rotate(180*(Math.PI/180));
ctx.drawImage(hidden, 200, 0, 200, 400, 0, -200, 200, 400);
};
</script>
</body>
</html>
Demo on jsFiddle