JSFiddle - React, Tailwind, and code Playground
by uemon
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.18/fabric.js"></script>
<div class="container">
<div id='canvascontain' width='1140' height='600' style='left:0px;background-color:rgb(240,240,240)'>
<canvas id="Canvas" width='600' height='500'></canvas>
</div>
<input type='button' id='tosvg_' value='create SVG'>
<div id='svgcontent'></div>
</div>
JavaScript
$(function(){
var canvas = new fabric.Canvas('Canvas',{
backgroundColor: '#ffffff',
preserveObjectStacking: true}
);
canvas.clipTo = function (ctx) {
ctx.arc(250, 300, 200, 0, Math.PI*2, true);
};
// Using a JQuery deferred object as a promise. This is used to
// synchronize execution, so that the SVG is never created before
// the image is added to the canvas.
var dImageLoaded = $.Deferred();
fabric.Image.fromURL('https://fabric-canvas.s3.amazonaws.com/Tulips.jpg', function(oImg) {
// Insert the image object below any existing objects, so that
// they appear on top of it. Then resolve the deferred.
canvas.insertAt(oImg, 0);
dImageLoaded.resolve();
});
canvas.add(new fabric.IText('Welcome ', {
left : fabric.util.getRandomInt(50,50),
top:fabric.util.getRandomInt(430, 430)
}));
canvas.renderAll();
$('#tosvg_').on('click',function(){
// Wait for the deferred to be resolved.
dImageLoaded.then(function () {
// Get the SVG string from the canvas.
var svgString = canvas.toSVG({
viewBox: {
x: 50,
y: 100,
width: 400,
height: 400,
},
width: 400,
height: 400,
});
// SVG content is not HTML, nor even standard XML, so doing
// $(svgString) might mutilate it. Therefore, even though we
// will be modifying the SVG before displaying it, we need to
// insert it straight into the DOM before we can get a JQuery
// selector to it.
// The plan is to hide the svgcontent div, append the SVG,
// modify it, and then show the svcontent div, to prevent the
// user from seeing half-baked SVG.
var $svgcontent = $('#svgcontent').hide().html(svgString);
console.log('$svgcontent', $svgcontent);
var $svg = $svgcontent.find('svg');
console.log('svg=', $svg);
// Create some SVG elements to represent the clip path, and
...