因此,我有一个非常简单的HTML,其中包含一个画布和一些按钮。当我单击绿色按钮或黄色时。我希望它可以更改笔刷的笔触颜色。当我单击按钮时,什么也没有发生。颜色保持不变。
这是我的脚本和HTML:JS + JQuery 1.7.2
var canvas;
$(function () {
canvas = window._canvas = new fabric.Canvas('canvas');
canvas.backgroundColor = '#efefef';
canvas.isDrawingMode= 1;
canvas.freeDrawingBrush.color = e.target.value;
canvas.freeDrawingBrush.width = 1;
canvas.renderAll();
document.getElementById('colorpicker').addEventListener('click', function (e) {
console.log(e.target.value);
canvas.freeDrawingBrush.color = e.target.value;
});
});
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<canvas id="canvas" width="400" height="400" class="canvas"></canvas>
<!--
<select name="colors" id="colorpick">
<option value="#FFFF00">Yellow</option>
<option value="#000000">Black</option>
<option value="#FF0000">Red</option>
</select>
-->
<div id= "colorpicker">
<button id= "yellow" value= "FFFF00">yellow</button>
<button id= "black" value= "000000">black</button>
<button id= "green" value = "#00ff00">green</button>
</div>
JSFiddle链接。正常运作。我猜是因为有JQuery。 http://jsfiddle.net/6zrm8tun/
答案 0 :(得分:2)
您的代码有两件事:
e
之前就引用了它,这是一个例外,请将其设置为默认值,例如canvas.freeDrawingBrush.color = 'green'
<button id="yellow" value="#FFFF00">
等答案 1 :(得分:0)
尝试这个伙伴-需要整理一些东西,但是我在jsfiddle中工作了。
var canvas;
var yellow = document.getElementById('yellow');
var black = document.getElementById('black');
var green = document.getElementById('green');
$(function () {
canvas = window._canvas = new fabric.Canvas('canvas');
canvas.backgroundColor = '#efefef';
canvas.isDrawingMode= 1;
canvas.freeDrawingBrush.color = 'green';
canvas.freeDrawingBrush.width = 1;
canvas.renderAll();
yellow.addEventListener('click', function (e) {
canvas.freeDrawingBrush.color = '#' + this.value;
});
black.addEventListener('click', function (e) {
canvas.freeDrawingBrush.color = '#' + this.value;
});
green.addEventListener('click', function (e) {
canvas.freeDrawingBrush.color = '#' + this.value;
});
});
<div id="colorpicker">
<button id="yellow" value="FFFF00">yellow</button>
<button id="black" value="000000">black</button>
<button id="green" value="00ff00">green</button>
</div>