I recently asked this question and got a working answer thanks to Durga (cheers). I'm trying to incorporate the same thing with Parcel.js and am running into a problem; the colorpicker itself changes and lets me choose a color- but the actual draw color doesn't change and I get this:
Uncaught TypeError: Cannot set property 'color' of undefined
at HTMLInputElement.change (module.js:1)
at Object.change (jquery.js:10365)
at updateOriginalInput (jquery.js:10365)
at HTMLSpanElement.paletteElementClick (jquery.js:10365)
at HTMLDivElement.dispatch (jquery.js:4011)
at HTMLDivElement.elemData.handle (jquery.js:3819)
My code looks like this:
index.html
<html>
<head>
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css">
</head>
<body>
<canvas id="canvas"></canvas>
<input type='text' id="toggle" />
<button id="btn-toggle"><i id='colorPalette' class="fas fa-palette"></i></button>
<script src="./app.js"></script>
</body>
</html>
module.js
export const createFabric = {
init: function () {
// create a wrapper around native canvas element (with id="c")
var canvas = new fabric.Canvas("canvas", {isDrawingMode: true,});
canvas.setHeight(500);
canvas.setWidth(500);
// create a rectangle object
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: "limegreen",
width: 120,
height: 120
});
// "add" rectangle onto canvas
canvas.add(rect);
}
};
app.js
import $ from "jquery";
import { fabric } from "fabric";
import { spectrum } from "spectrum-colorpicker";
import { createFabric } from "./module";
$(function() {
createFabric.init();
// Color Picker
$("#toggle").spectrum({
showPaletteOnly: true,
showPalette: true,
color: 'black',
hideAfterPaletteSelect: true,
palette: [
['black'],
['blue'],
['red']
],
change: function(selectedColor) {
//$("#colorValue").val(selectedColor);
canvas.freeDrawingBrush.color = selectedColor.toHexString();
$("#colorPalette").css("color", selectedColor.toHexString())
}
});
$("#btn-toggle").click(function() {
$("#toggle").spectrum("toggle");
return false;
});
});
style.css
@import "bulma/css/bulma.css";
@import "spectrum-colorpicker/spectrum.css";
canvas {
border: 1px solid #dddd;
margin-top: 10px;
}
.sp-replacer {
display: none !important;
}
.sp-container {
border-color: grey;
}
.sp-thumb {
border-color: grey;
}
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bulma": "^0.7.1",
"fabric": "^2.3.3",
"jquery": "^3.3.1",
"spectrum-colorpicker": "^1.8.0"
}
}
What am I doing wrong here?
In your module.js assign your canvas value to window object
var canvas = window._canvas = new fabric.Canvas("canvas", {isDrawingMode: true,});
And then in app.js get canvas using var canvas = window._canvas;