Reputation: 61
I am adding my cropped image and logo on fabric canvas, cropped image and logo are lower and upper canvas. Now the problem is how to set max width to fabric canvas so that i can drag logo through out the canvas.
I have implemented max width to existing canvas, logo and cropped image. Here the problem is i am unable to drag the logo to entire canvas.
Here is the code
<div class="container">
<div style="position: relative;" id="editor">
<canvas id="canvas" class="img-responsive"></canvas>
</div>
<div class="container">
<a class="btn btn-primary" id="save">Save</a>
<a class="btn btn-primary" id="download">Download</a>
<script>
$(function () {
var source = sessionStorage.getItem("source");
$("#background").attr("src", source);
});
setTimeout(function () {
var myImg = document.querySelector("#background");
var realWidth = myImg.naturalWidth;
var realHeight = myImg.naturalHeight;
$("canvas").attr("width", realWidth);
$("canvas").attr("height", realHeight);
var source = document.getElementById('background').src;
var canvas = new fabric.Canvas('canvas');
canvas.width=realWidth;
canvas.height=realHeight;
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'images/logo.png';
var imgInstance = new fabric.Image(img, {
width: 200
, height: 45
});
canvas.add(imgInstance);
canvas.setBackgroundImage(source, canvas.renderAll.bind(canvas), {
backgroundImageOpacity: 0.5
, backgroundImageStretch: false
});
}, 2000);
$("#save").click(function(){
function blobCallback(iconName) {
return function (b) {
var a = document.getElementById('download');
a.download = iconName + ".jpg";
a.href = window.URL.createObjectURL(b);
}
}
canvas.toBlob(blobCallback('wallpaper'), 'image/vnd.microsoft.jpg', '-moz-parse-options:format=bmp;bpp=32');
});
Upvotes: 3
Views: 3712
Reputation: 14741
being a fabricjs canvas, do not manipulate width and height directly but use the proper method:
setTimeout(function () {
var myImg = document.querySelector("#background");
var realWidth = myImg.naturalWidth;
var realHeight = myImg.naturalHeight;
var source = document.getElementById('background').src;
var canvas = new fabric.Canvas('canvas');
canvas.setDimensions({ width: realWidth, height: realHeight });
var img = new Image();
// use a load callback to add image to canvas.
img.src = 'images/logo.png';
var imgInstance = new fabric.Image(img, {
width: 200
, height: 45
});
canvas.add(imgInstance);
canvas.setBackgroundImage(source, canvas.renderAll.bind(canvas), {
backgroundImageOpacity: 0.5
, backgroundImageStretch: false
});
}, 2000);
Upvotes: 2