Reputation: 31
I am trying to create image from FabricJS canvas using canvas.toDataURL();
I have php code which writes actual image file from this datauri.
This function creates base64 data uri from the canvas. At normal resolutions (tested upto full HD) this generates actual size image which i have set (50pxX50px). But at 4k resolution somehow it generates double size image. I tried setting multiplier, height, width option but no luck.
I have created a jsfiddle here
var canvas = new fabric.Canvas('myCanvas');
canvas.setHeight(50);
canvas.setWidth(50);
canvas.setBackgroundColor('rgb(59,173,160)');
// create a rectangle object
var rect = new fabric.Rect({
left: 0,
top: 0,
fill: 'blue',
width: 20,
height: 20
});
// "add" rectangle onto canvas
canvas.add(rect);
var img = canvas.toDataURL({
format: 'png',
multiplier: 1,
left: 0,
top: 0,
width: 50,
height: 50
});
console.log(img);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.3/fabric.min.js"></script>
<canvas id="myCanvas" style="border: 2px solid red;">
Your browser does not support the HTML5 canvas tag.
</canvas>
I have console the output so that you can check.
Please help me with this.
Upvotes: 3
Views: 5188
Reputation: 3706
You have high pixel density monitor, that's why you have this issue. Read this short topic at developer.mozilla.org about device pixel ratio.
You should divide your width and height by the pixel ratio of the device.
Try this:
var ratio = window.devicePixelRatio;
var img = canvas.toDataURL(
{
format: 'png',
multiplier: 1,
left: 0,
top: 0,
width: 50 / ratio ,
height: 50 / ratio
});
Upvotes: 5