FabricJS, change control button image when hover - javascript

I am using a custom rotation icon that shows when I select objects, defined as I create the canvas.
function renderRotationIcon(ctx, left, top, styleOverride, fabricObject) {
//#ts-ignore
let size = this.cornerSize
ctx.save()
ctx.translate(left, top)
//#ts-ignore
ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle))
ctx.drawImage(img, -size / 2, -size / 2, size, size)
ctx.restore()
}
However, I would like to change the image img when the user hovers the rotation icon.
I tried this when defining img
img.onmouseover = () => {
img.src = "LibraryHoverTrans.png"
}
As expected, this didn't work, as I suspect that something more specific to fabricJS is needed. I tried searching for a related solution.

Related

javascript canvas only drawing second image if the browser window is resized

i am using react, I have a canvas with a green square in the middle and a red rectangle drawn to the left of it. The problem is only the first rectangle is being drawn, if I resize the browser the other one gets drawn.
const Canvas = props => {
useEffect(() =>{
var player1 = { x: playerX, y: playerY, draggable: gameStatus }
var enemy1 = { x: enemy1X, y: enemy1Y, width: enemy1Width, height: enemy1Height}
const drawFun = () => {
context.clearRect(0,0, canvasWidth, canvasHeight)
context.beginPath();
context.fillStyle = '#00f4cc'
context.fillRect(player1.x, player1.y, playerWidth, playerHeight)
context.beginPath();
context.fillStyle = 'red'
context.fillRect(enemy1.x, enemy1.y, enemy1Width, enemy1Height)
requestAnimationFrame(drawFun);
}
drawFun();
The second red square gets drawn where it should be, I just need to resize the browser window to confirm it. Im not sure why resizing window helps,any help appreciated!
I would guess that the coordinates of where you are trying to draw the rectangles are out of the browser window (or the dimensions defined by the canvas). However, this if this is being solved by resizing the browser window then this is probably not the case because the canvas would always start at (0,0).
I would suggest printing out the enemy.x
console.log(enemy.x);
If the value is negative, then the rectangle is being cut off.
I'm not sure if this is the actual cause, but hope it helps

Unexpected border pattern in a grid with rectangles in p5.js

I am trying to generate a square grid like pattern in p5js that covers as much of the browser window as possible.I am using p5js in instance mode as I using this with react and I am using chrome in Win10.
Here is my code:-
var size = 15;
var height = window.innerHeight;
var width = window.innerWidth;
Sketch = (p) => {
p.setup = () => {
p.createCanvas(width,height)
p.frameRate(60);
p.noLoop();
}
p.draw = () => {
p.background(250);
p.stroke(0);
p.noFill();
for(let i =0;i*size +size <width;i++) {
for(let j=0;j*size +size<height;j++) {
p.rect(i*size,j*size,size,size);
}
}
}
p.mouseDragged = (e) => {
p.stroke(0);
let x = Math.floor(e.clientY/size);
let y = Math.floor(e.clientX/size);
p.fill(220);
p.rect(y*size,x*size,size,size);
}
}
I call p.noLoop() so it doesnt refreshes everytime and I also have a button that calls p.redraw() to change everything to default. Here is the grid and behaviour I get:
The borders of grids are of varying sizes, first they decrease then increase then decrease and so on. Also, the area around which I drag my mouse has even more weird borders(This gets resolved when I click somewhere else so is this a GPU Aliasing rendering issue?). How do I create grid with same borders throughout my screen?
Edit: When I render even a single box, it has issues. The left and upper border are fine. However the right and down borders have an extra pixel of grayish borders which seems to be the problem. How do I fix this?
Also, How does strokeWeight and rect work in p5js? If I do strokeWeight(10) and rect(3,2,50,50), does that create a 50 by 50 rectangle with 10 pixels borders all around or the borders are included in the rectangle size?

Javascript SVG clipto with clip rule (fabricjs)

There is the exemple in img
http://imgur.com/rFdcctc
I have a background where i put an image (phone case).
After that i put a rectangle on the top side (50% top). (canvas)
On that i put an svg that is an another mask (that follow the case curves).
The svg is the same as the entire background in size. So to only have the top of the SVG i "clip" a rectangle on to it.
var clipTo = function(ctx) {
var w = mask.width, h = mask.height;
var x = -w/2, y = -h/2;
var rx = 0, ry = 0;
ctx.moveTo(x+rx, y);
ctx.lineTo(x+w-rx, y);
ctx.lineTo(x+w, y+(h/2)-ry);
ctx.lineTo(x+rx,y+(h/2));
ctx.lineTo(x,y+ry);
ctx.closePath();
};
mask.setClipTo(clipTo);
And it works fine. But when i put a dragable image on it the image is mask by the SVG but not the clip rectangle, as if the clip is still there. (in the image, the content of the red rectangle should be invisible)
I have found that there is a clip-rule :
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clip-rule
that could maybe with luck enventually should do it, but i have no idea how to apply it in javascript (i use fabricjs)
So if someone has an idea... :)
Thank you

jQuery and Canvas loading behaviour

After being a long time lurker, this is my first post here! I've been RTFMing and searching everywhere for an answer to this question to no avail. I will try to be as informative as I can, hope you could help me.
This code is for my personal webpage.
I am trying to implement some sort of a modern click-map using HTML5 and jQuery.
In the website you would see the main image and a hidden canvas with the same size at the same coordinates with this picture drawn into it.
When the mouse hovers the main picture, it read the mouse pixel data (array of r,g,b,alpha) from the image drawn onto the canvas. When it sees the pixel color is black (in my case I only check the RED value, which in a black pixel would be 0) it knows the activate the relevant button.
(Originally, I got the idea from this article)
The reason I chose this method, is for the page to be responsive and dynamically change to fit different monitors and mobile devices. To achieve this, I call the DrawCanvas function every time the screen is re-sized, to redraw the canvas with the new dimensions.
Generally, this works OK. The thing is ,there seems to be an inconsistent behavior in Chrome and IE(9). When I initially open the page, I sometimes get no pixel data (0,0,0,0), until i re-size the browser. At first I figured there's some loading issues that are making this happen so I tried to hack it with setTimeout, it still doesn't work. I also tried to trigger the re-size event and call the drawCanvas function at document.ready, still didn't work.
What's bothering me is most, are the inconsistencies. Sometimes it works, sometimes is doesn't. Generally, it is more stable in chrome than in IE(9).
Here is the deprecated code:
<script type="text/javascript">
$(document).ready(function(){setTimeout(function() {
// Get main image object
var mapWrapper = document.getElementById('map_wrapper').getElementsByTagName('img').item(0);
// Create a hidden canvas the same size as the main image and append it to main div
var canvas = document.createElement('canvas');
canvas.height = mapWrapper.clientHeight;
canvas.width = mapWrapper.clientWidth;
canvas.fillStyle = 'rgb(255,255,255)';
canvas.style.display = 'none';
canvas.id = 'hiddencvs';
$('#map_wrapper').append(canvas);
// Draw the buttons image into the canvas
drawCanvas(null);
$("#map_wrapper").mousemove(function(e){
var canvas = document.getElementById('hiddencvs');
var context = canvas.getContext('2d');
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
// Get pixel information array (red, green, blue, alpha)
var pixel = context.getImageData(x,y,1,1).data;
var red = pixel[0];
var main_img = document.getElementById('map_wrapper').getElementsByTagName('img').item(0);
if (red == 0)
{
...
}
else {
...
}
});
},3000);}); // End DOM Ready
function drawCanvas(e)
{
// Get context of hidden convas and set size according to main image
var cvs = document.getElementById('hiddencvs');
var ctx = cvs.getContext('2d');
var mapWrapper = document.getElementById('map_wrapper').getElementsByTagName('img').item(0);
cvs.width = mapWrapper.clientWidth;
cvs.height = mapWrapper.clientHeight;
// Create img element for buttons image
var img = document.createElement("img");
img.src = "img/main-page-buttons.png";
// Draw buttons image inside hidden canvas, strech it to canvas size
ctx.drawImage(img, 0, 0,cvs.width,cvs.height);
}
$(window).resize(function(e){
drawCanvas(e);
}
);
function findPos(obj)
{
...
}
</script>
I'd appreciate any help!
Thanks!
Ron.
You don't wait for the image to be loaded so, depending on the cache, you may draw an image or not in the canvas.
You should do this :
$(function(){
var img = document.createElement("img");
img.onload = function() {
var mapWrapper = document.getElementById('map_wrapper').getElementsByTagName('img').item(0);
...
// your whole code here !
...
}
img.src = "img/main-page-buttons.png";
});

Is there a way to use JCrop to crop an area larger than the actual image?

From what I can tell, JCrop will not let me set things up so the user can crop outside the actual image and include surrounding whitespace. Is there a way to do that?
To help explain what I mean, say we are restricting our crop to a 16:9 ratio. That works fine for an image with a naturally wide subject:
But sometimes the source image that a user wants to use does not comfortably accommodate the desired ratio:
Instead, we'd like to allow them to include space outside the image by making the crop area larger than the image itself:
I've been messing around with JCrop and looking through the manual and Google for a while and it doesn't look like this is possible (without modifying JCrop). Am I wrong? If so, how do you do it?
FWIW, the actual images in this case will be product/organization logo images, which come in a large variety of aspect ratios, and almost always the images available to people have almost no whitespace around the text/imagery. Which means any fixed aspect ratio crop restricted to the bounds of the image will almost certainly chop off either the top+bottom or left+right sides of the image.
My solution was to create a temporary canvas with square dimensions equal to the largest side of the image. I made the canvas background white and added the image in the center. Then I created a new image and used the canvas as the image source. Then I used that image with jcrop. It's slower, but it works!
Here's an example:
img.onload = function(){
// get the largest side of the image
// and set the x and y coordinates for where the image will go in the canvas
if( img.width > img.height ){
var largestDim = img.width;
var x = 0;
var y = (img.width-img.height)/2;
}
else{
var largestDim = img.height;
var y = 0;
var x = (img.height-img.width)/2;
}
// create a temporary canvas element and set its height and width to largestDim
canvastemp = document.createElement("canvas");
canvastemp.width = canvastemp.height = largestDim;
var ctx = canvastemp.getContext('2d');
// set the canvas background to white
ctx.fillStyle="#FFFFFF";
ctx.fillRect(0, 0, canvastemp.width, canvastemp.height);
// center the image in the canvas
ctx.drawImage(img, x, y, img.width, img.height);
// create a new image and use the canvas as its source
var squaredImg = document.createElement("img");
squaredImg.src = canvastemp.toDataURL();
// add jcrop once the image loads
squaredImg.onload = function(){
addJcrop(squaredImg);
}
};
function addJcrop(img){
// your jcrop code
}
This way users can choose to include the entire image in the crop if they wish.
consider using something like php imagick to convert the photo to photo + transparent big background and then put that to JCrop I dont think its possible other way
You could fool the jCrop script. Instead of showing image.jpg, you do something like not_a_real_image.php?imagename=image.jpg.
Then give the php file a header of the image, and a width and height, and align the actual image in the center of that.
All you have to do is remember the amount of canvas you've added to correct it later on.
I made a function using Imagick:
function resizeImage($imgSrc, $width, $height, $createBg, $output, $show) {
$img = new Imagick($imgSrc);
if ($img->getImageWidth() / $img->getImageHeight() < $width / $height) {
$img->thumbnailImage(0, $height);
} else {
$img->thumbnailImage($width, 0);
}
$canvas = new Imagick();
$canvas->newImage($width, $height, 'white', 'jpg');
/* Creates a background image (good for vertical images in horizontal canvas or vice-versa) */
if ($createBg) {
$imgBg = new Imagick($imgSrc);
if ($imgBg->getImageWidth() / $imgBg->getImageHeight() < $width / $height) {
$imgBg->thumbnailImage($width, 0);
} else {
$imgBg->thumbnailImage(0, $height);
}
$imgBg->blurImage(0, 80);
$geometryBg = $imgBg->getImageGeometry();
$xBg = ( $width - $geometryBg['width'] ) / 2;
$yBg = ( $height - $geometryBg['height'] ) / 2;
$canvas->compositeImage( $imgBg, imagick::COMPOSITE_OVER, $xBg, $yBg );
}
/* Center image */
$geometry = $img->getImageGeometry();
$x = ( $width - $geometry['width'] ) / 2;
$y = ( $height - $geometry['height'] ) / 2;
$canvas->compositeImage( $img, imagick::COMPOSITE_OVER, $x, $y );
/* Save image */
if ($output) {
$canvas->writeImage($output);
}
/* Show the image */
if ($show) {
header( 'Content-Type: image/jpg' );
echo $canvas;
}
}
The comment's explain it all, enjoy!

Categories

Resources