set width and height of canvas in fabric.js - javascript

I have an image background in my HTML5 canvas.
var canvas = new fabric.Canvas('#canvas1');
canvas.setBackgroundImage(
'http://fabricjs.com/assets/jail_cell_bars.png',
canvas.renderAll.bind(canvas)
);
How to set dimensions of my canvas (width, height) to the dimensions of the background image?
Thanks.

I think the above answer does not use fabric.js, it uses normal canvas.
When you use fabric.js and its Fabric.Canvas class, the code should be:
image.onLoad = function() {
var fabric_canvas = new fabric.Canvas('canvas1');
fabric_canvas.setDimensions({width:image.width, height:image.height});
};
In my case,
var canvas = new fabric.Canvas("test_fabric");
canvas.setDimensions({width:800, height:200});
The result is:
<canvas id="test_fabric" width="800" height="200" class="lower-canvas" style="position: absolute; width: 800px; height: 200px; left: 0px; top: 0px; -webkit-user-select: none;"></canvas>
Both canvas.width and canvas.style.width are set.

These work as well!
canvas.setWidth(500);
canvas.setHeight(400);

You can use CSS or dom properties to set the dimensions of your canvas. If you know the dimensions of your image, you can do it in a stylesheet:
#canvas1 { width: XXXpx; height: YYYpx; }
Or in the dom:
<canvas id="canvas1" width="XXX" height="YYY"></canvas>
If the image is dynamic and want to set the dimensions in JS, you do something like this:
var image = new Image()
image.src = 'http://fabricjs.com/assets/jail_cell_bars.png';
image.onLoad = function () {
var canvas = document.getElementById('canvas1');
canvas.width = image.width;
canvas.height = image.height;
};

Related

How do I embed an image on a canvas (HTML/JS)

I am trying to embed an image into a canvas so that I can draw lines over the image with the canvas. However, I can't seem to get the image to appear inside the canvas. Here's the code I have (HTML then JS):
<canvas id="myCanvas" style="border:1px solid #d3d3d3; position: relative; z-index:3; top:10em; width: 30em; height: 20em; left: 22em;"></canvas>
<img src="mapfinal.png" id="mapPic" style="display: none;"/>
javascript
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var map = document.getElementById("mapPic");
ctx.drawImage(map, 20, 20);
Thank you so much for any help!
It could be one of two things. The most likely issue is that the image is not yet loaded before you try to draw it. To fix this, add an onload event listener to the img element to draw it once the image has loaded.
<img src="mapfinal.png" id="mapPic" onload="drawCanvas" style="display: none;"/>
<script>
function drawCanvas() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var map = document.getElementById("mapPic");
ctx.drawImage(map, 20, 20);
}
</script>
The other issue might be that since the img element is set to display: none the browser isn't loading the image at all. Depending on the browser it may or may not load it. If you don't want the image to dispaly a better approach would be to create it through JavaScript.
var map = new Image();
map.onload = function() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.drawImage(map, 20, 20);
};
map.src = 'mapfinal.png';

Create a seamless image crop over original image with canvas

I'm trying to crop an image using a canvas, and position that crop over the original image in a seamless way, so that the separation wouldn't be visible.
Here's what I would have expected to work:
const image = document.querySelector("img")
const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")
canvasCoords = canvas.getBoundingClientRect()
ctx.drawImage(
image,
canvasCoords.left, canvasCoords.top,
canvasCoords.width, canvas.height,
0, 0,
canvasCoords.width, canvasCoords.height
)
I want the crop to fill my canvas, hence the last 4 properties. canvasCoords. Also I am aware that a real-life solution would involve getting the canvas offset relatively to the image, but this is just a simplified example.
Here is a JS Fiddle of that example.
Calculate the width and height scales using image.naturalWidth / image.width and image.naturalHeight / image.height like below:
const image = document.querySelector("img")
const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")
canvasCoords = canvas.getBoundingClientRect()
const widthScale = image.naturalWidth / image.width
const heightScale = image.naturalHeight / image.height
ctx.drawImage(
image,
canvasCoords.left * widthScale, canvasCoords.top * heightScale,
canvasCoords.width * widthScale, canvas.height * heightScale,
0, 0,
canvasCoords.width, canvasCoords.height
)
body {
margin: 0;
}
div {
position: relative;
}
img {
position: absolute;
top: 0;
left: 0;
width: 500px;
height: 300;
}
canvas {
position: absolute;
top: 140px;
left: 175px;
border: 2px solid red;
}
<div>
<img src="http://www.savoie-mont-blanc.com/var/smb/storage/images/media/images/visites-et-decouvertes/nature/lac-des-vaches-a-pralognan-la-vanoise-parc-national-de-la-vanoise/359903-1-fre-FR/Lac-des-Vaches-a-Pralognan-la-Vanoise-Parc-national-de-la-Vanoise_default_format.jpg">
<canvas width="150" height="50"></canvas>
</div>
If you can hide the image from the page and do everything in the canvas, you can use the trick of drawing the canvas again:
ctx.drawImage(
canvas,
0, 0,
150,50,
0,0,150,50
)
JS Fiddle

Any way to achieve CSS 3D transform with javascript?

I want to rotate an image in 3D and this is possible in css with
transform: perspective(50px) rotateX(10deg) rotateY(10deg) rotateZ(10deg);
Currently I am using a canvas and the .style.transform property does not work for me. Example: https://jsfiddle.net/chung9ey/31/ . Note: I don't want to have a css file or style tags at all.
Your code is basically correct, but instead of img.style.transform, transform the canvas with canvas.style.transform:
var img = new Image;
var canvas = document.getElementById("hello");
var context = canvas.getContext("2d");
img.onload = function(){
canvas.style.transform = "perspective(50px) rotateX(10deg) rotateY(10deg) rotateZ(10deg)";
context.drawImage(img, 0 ,0, 500, 300);
}
img.src = "https://www.enterprise.com/content/dam/global-vehicle-images/cars/CHRY_200_2015.png";
<canvas id = "hello" width = "500px" height = "300px" style="border: 1px solid BLACK";></canvas>

How to add image to canvas using fabric js

I am trying to add images to canvas using fabric.js. I want to add a image every time the button is clicked. The image is stored in my computer. When the image is added to the canvas, I would like to be able to drag it over the canvas.
Here is my javascript code:
function addimage1() {
var canvas = new fabric.Canvas('c');
var img = document.createElement("img");
img.src = url_1;
img.height = 50;
img.width = 100;
//optionally set a css class on the image
// var class_name = "foo";
// img.setAttribute("class", class_name);
var imgInstance = new fabric.Image(img, {
left: 100,
top: 100,
angle: 30,
opacity: 0.85
});
canvas.add(imgInstance);
//document.getElementById("resizable").appendChild(img);
//document.body.appendChild(img);
}
and here is the html code for button and canvas:
<div class="description">
<canvas id="c" width="710" height="600" style="background-color: #ffffff" ></canvas>
</div>
What am I doing wrong so the image wont be displayed?

blurred text when a canvas is placed on top of another canvas

I want to display the mouse's x position on canvas as mouse moves. Can someone please tell why the text is so big and blurry and also is there any way to achieve the transparency between these two canvases
<body style="margin: 0; padding: 0; height: 100%; width: 100%; overflow: hidden;">
<canvas id="myCanvas" style="display: block; height: 100%; width: 100%;">
Your browser does not support the HTML5 canvas tag.</canvas> <canvas id="temp">
Your browser does not support the HTML5 canvas tag.</canvas>
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var hgap = 0;
var vgap = 0;
var rows, cols;
var annotation_x = 1;
var row = 0; var col = 0;
//ctx.font = "14px Arial";
var t = document.getElementById("temp");
tctx = t.getContext("2d");
// tctx.lineWidth = 10;
tctx.lineJoin = 'round';
tctx.lineCap = 'round';
tctx.strokStyle = 'red';
var mouse = { x: 0, y: 0 };
c.addEventListener('mousemove', function (evt) {
// tctx.clearRect(0, 0, c.width, c.height);
ctx.clearRect(0, 0, c.width, c.height);
mouse.x = evt.pageX;
mouse.y = evt.pageY;
ctx.fillText(mouse.x, 10, 10);
}, false);
</script>
</body>
The problem isn't due to having two canvas.
The problem is that you scale your canvas using CSS, but you don't modify its number of pixels (height and width attributes). Then, the result is blurry.
If you don't scale it with CSS, the result is fine: Demo
Alternatively, you can try using image-rendering CSS property (e.g. crisp-edges, demo)
You can also modify height and width attributes when the browser is resized (resize event), and redraw the canvas.
<canvas id="myCanvas" style="display: block; height: 100%; width: 100%;">
^ You shouldn't scale a canvas element with CSS unless you want it's contents to be interpolated. Consider a 300x125px image, which you've scaled to the width and height of the browser window - the image will become blurry.
If you wish to have a full-screen canvas you need to scale it with JS:
var c = document.getElementById("myCanvas");
c.width = window.innerWidth;
c.height = window.innerHeight;
..or with HTML:
<canvas width="1920" height="1080"></canvas>

Categories

Resources