Trying to use Rough.js to render parts of a konva Stage but without success. Rough uses a reference to the canvas to draw to, but neither getCanvas() nor toCanvas() on a konva layer seems to do the trick. Ideas?
// Combined code
const cstage = new Konva.Stage({
container: 'roughAndKonva',
width: 200,
height: 200
});
const clayer = new Konva.Layer();
var konvaCanvas = clayer.getCanvas()
const crc = rough.canvas(konvaCanvas);
crc.rectangle(50, 50, 100, 100);
cstage.add(clayer);
Fiddle here: https://jsfiddle.net/qwLmb9ge/1/
I used the answer by Vanquished Wombat above to get started, but ran into some problems with re-drawing the scene as the new rectangle drawn would then be erased.
Solved this by drawing the rough-Rectangle onto a SVG and then converting the SVG to and Image that can be added onto Konva. This makes it fit snuggly into the Konva JS routines, including redraws.
// Background box
const svg = $('<svg xmlns="http://www.w3.org/2000/svg"></svg>')[0];
svg.setAttribute("height", startWidth);
svg.setAttribute("width", startHeight);
const rc = rough.svg(svg);
svg.appendChild(rc.rectangle(0, 0, startWidth, startHeight, {roughness: 0.3, strokeWidth: 2}));
svgToImg(svg).then(background => {
const bgImage = new Konva.Image({
x: 0,
y: 0,
image: background,
name: 'depLine',
width: background.width,
height: background.height
});
board.add(bgImage);
board.draw();
});
svgToImg function:
// Promise to convert SVG to Image
function svgToImg(svg) {
return new Promise((resolve, reject) => {
const img = new Image();
const svgBlob = new Blob([svg.outerHTML], {type:'image/svg+xml'});
const url = DOMURL.createObjectURL(svgBlob);
img.onload = function() {
DOMURL.revokeObjectURL(url);
resolve(this);
};
img.onerror = reject
img.src = url;
});
}