I am using Fabric.js to draw rectangles on a canvas. After drawing a rectangle, I want to disable all events on that object. I have tried to do it using canvas.__eventListeners["mouse:down"] = []; but then after the object selection is cleared, the canvas can't apply any events.
<html lang="en" >
<head>
<meta charset="utf-8" />
<title>HTML5 canvas - Image color picker | Script Tutorials</title>
<link href="index.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.1.0/fabric.all.min.js" ></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="column1">
<canvas id="panel" width="700" height="350"></canvas>
</div>
<div style="clear:both;"></div>
<div id="log"></div>
</div>
</body>
<script>
(function() {
var canvas = new fabric.Canvas('panel');
var clicks=0;
var x1=0;var y1=0;
var rect;
canvas.on('mouse:down', function(e){
//check if you clicked on an object that exists canvas
if(e.target == undefined){
if (clicks == 0) {
var pointer=canvas.getPointer(event.e);
console.log(pointer);
x1 = pointer.x;
y1 =pointer.y;
console.log("Start Pointer " +x1 ,y1);
clicks++;
}
else
{
var endpointer=canvas.getPointer();
console.log(endpointer);
var endx=endpointer.x;
var endy=endpointer.y;
console.log("Endpointer " +endx ,endy);
console.log("x and y"+x1,y1);
var newwidth=endpointer.x- x1;
var newheight=endpointer.y - y1;
rect=new fabric.Rect({
left:x1,
top: y1,
originX :'left',
originY :'top',
width:newwidth,
height:newheight,
selectable: true,
evented:false,
fill:'red',
opacity :0.3
});
canvas.add(rect);
//console.log(rect.setWidth(pointer2.x- x1 ));
//console.log(rect.setHeight( pointer2.y - y1));
canvas.renderAll();
clicks=0;
}
}
else
{
//canvas.getActiveObject().remove();
canvas.__eventListeners["mouse:down"] = [];
}
});
canvas.on('object:moving',function(){
var bound=rect.getBoundingRect();
console.log(bound.left,bound.top,bound.width,bound.height);
});
canvas.on('object:scaling',function(){
var bound=rect.getBoundingRect();
console.log(bound.left,bound.top,bound.width,bound.height);
});
canvas.on('object:selected',function(e){
document.onkeydown = function(e) {
if (e.keyCode === 27||e.button==3) {
e.preventDefault();
canvas.getActiveObject().remove();
}
}
});
fabric.Image.fromURL('fedex.jpg', function (img) {
canvas.add(img.set({
width: 700,
height:350,
left: 350,
top: 175,
selectable: false,
}));
});
})();
</script>
With the method canvas.off('mouse:down', eventHandler) event handlers registered using canvas.on('mouse:down', eventHandler) can be removed. Be sure to pass the same function into both calls (e.g. by assigning the handler to a variable).
This method is available on all Observables in fabric (see API doc: http://fabricjs.com/docs/fabric.Observable.html#off)
What is the final answer? We're basing our decision to mousedown on or mousedown off, based on the event - if it has a target. I came up with this solution (a 2nd mousedown handler), but it didn't work.
canvas.on('mouse:down', function (e) {
// canvas click, not object click; so create the obj
if (e.target === undefined) {
canvas.on('mouse:down', eventHandler);
}
else {
// an object was clicked, so don't create the obj again
canvas.off('mouse:down', eventHandler);
}
});
Where eventHandler is the function that handles object creation.
Related
I have created a simple html using the draggable marker example from here maps. I have adapted it to support IE 11 by adding reference to legacy js, meta tag and using P2D engine in map options. Also added two url parameters for coordinates. It works perfectly in IE11 and it loads and shows pan and zoom buttons in ms-access webbrowser but it keeps static, it's not draggable, but pan and zoom works.
The curious thing is that if I navigate to wego.here.com in the same webbrowser control then the map is draggable. So they're doing something else in the here maps main page that I'm not doing in my script.
I have also tried using Microsoft Web Browser from the activex controls list in access.
I need it to be draggable so I can pick the coordinates after the user changes the marker position.
This is my script:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Draggable Marker</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-core-legacy.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-service-legacy.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script>
<script src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>
<style>
html, body { margin:0px; padding:0px; width: 100%; height: 100%; }
.main { height: 100%; }
</style>
</head>
<body id="markers-on-the-map">
<div class="main" style="width:100%" id="map"></div>
<input type="hidden" id="long" name="long">
<input type="hidden" id="lat" name="lat">
<script>
function addDraggableMarker(map, behavior){
var marker = new H.map.Marker({lat:latitud, lng:longitud}, {volatility: true});
// Ensure that the marker can receive drag events
marker.draggable = true;
map.addObject(marker);
// disable the default draggability of the underlying map
// and calculate the offset between mouse and target's position
// when starting to drag a marker object:
map.addEventListener('dragstart', function(ev) {
var target = ev.target,
pointer = ev.currentPointer;
if (target instanceof H.map.Marker) {
var targetPosition = map.geoToScreen(target.getGeometry());
target['offset'] = new H.math.Point(pointer.viewportX - targetPosition.x, pointer.viewportY - targetPosition.y);
behavior.disable();
}
}, false);
// re-enable the default draggability of the underlying map
// when dragging has completed
map.addEventListener('dragend', function(ev) {
var target = ev.target;
if (target instanceof H.map.Marker) {
$('#long').val(ev.target.b.lng);
$('#lat').val(ev.target.b.lat);
behavior.enable();
}
}, false);
// Listen to the drag event and move the position of the marker
// as necessary
map.addEventListener('drag', function(ev) {
var target = ev.target,
pointer = ev.currentPointer;
if (target instanceof H.map.Marker) {
target.setGeometry(map.screenToGeo(pointer.viewportX - target['offset'].x, pointer.viewportY - target['offset'].y));
}
}, false);
}
/**
* Boilerplate map initialization code starts below:
*/
//Step 1: initialize communication with the platform
// In your own code, replace variable window.apikey with your own apikey
var platform = new H.service.Platform({
apikey: '?????????????????????????????????'
});
var defaultLayers = platform.createDefaultLayers();
//url parameters
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
var latitud=query_string.lat;
var longitud=query_string.long;
//Step 2: initialize a map - this map is centered over Boston
var map = new H.Map(document.getElementById('map'),
defaultLayers.raster.normal.map, {
center: {lat:latitud, lng:longitud},
engineType: H.map.render.RenderEngine.EngineType.P2D,
zoom: 12,
pixelRatio: window.devicePixelRatio || 1
});
// add a resize listener to make sure that the map occupies the whole container
//window.addEventListener('resize', () => map.getViewPort().resize());
window.addEventListener('resize', function () {map.getViewPort().resize(); });
//Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
//var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Step 4: Create the default UI:
var ui = H.ui.UI.createDefault(map, defaultLayers, 'en-US');
// Add the click event listener.
addDraggableMarker(map, behavior);
</script>
</body>
</html>```
Check please on this static page
: your code works for my IE11
I need a div you can click in the corner and resize on android and iphone
thanks for your help
Here is my solution. This code works with Firefox, Chrome, IPad and Android. Just click on the corner.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>resizable demo</title>
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style>
#resizable {
width: 100px;
height: 100px;
background: #ccc;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript">
(function ($) {
// Detect touch support
$.support.touch = 'ontouchend' in document;
// Ignore browsers without touch support
if (!$.support.touch) {
return;
}
var mouseProto = $.ui.mouse.prototype,
_mouseInit = mouseProto._mouseInit,
touchHandled;
function simulateMouseEvent (event, simulatedType) { //use this function to simulate mouse event
// Ignore multi-touch events
if (event.originalEvent.touches.length > 1) {
return;
}
event.preventDefault(); //use this to prevent scrolling during ui use
var touch = event.originalEvent.changedTouches[0],
simulatedEvent = document.createEvent('MouseEvents');
// Initialize the simulated mouse event using the touch event's coordinates
simulatedEvent.initMouseEvent(
simulatedType, // type
true, // bubbles
true, // cancelable
window, // view
1, // detail
touch.screenX, // screenX
touch.screenY, // screenY
touch.clientX, // clientX
touch.clientY, // clientY
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
0, // button
null // relatedTarget
);
// Dispatch the simulated event to the target element
event.target.dispatchEvent(simulatedEvent);
}
mouseProto._touchStart = function (event) {
var self = this;
// Ignore the event if another widget is already being handled
if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
return;
}
// Set the flag to prevent other widgets from inheriting the touch event
touchHandled = true;
// Track movement to determine if interaction was a click
self._touchMoved = false;
// Simulate the mouseover event
simulateMouseEvent(event, 'mouseover');
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
// Simulate the mousedown event
simulateMouseEvent(event, 'mousedown');
};
mouseProto._touchMove = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Interaction was not a click
this._touchMoved = true;
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
};
mouseProto._touchEnd = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Simulate the mouseup event
simulateMouseEvent(event, 'mouseup');
// Simulate the mouseout event
simulateMouseEvent(event, 'mouseout');
// If the touch interaction did not move, it should trigger a click
if (!this._touchMoved) {
// Simulate the click event
simulateMouseEvent(event, 'click');
}
// Unset the flag to allow other widgets to inherit the touch event
touchHandled = false;
};
mouseProto._mouseInit = function () {
var self = this;
// Delegate the touch handlers to the widget's element
self.element
.on('touchstart', $.proxy(self, '_touchStart'))
.on('touchmove', $.proxy(self, '_touchMove'))
.on('touchend', $.proxy(self, '_touchEnd'));
// Call the original $.ui.mouse init method
_mouseInit.call(self);
};
})(jQuery);
</script>
<div id="resizable"></div>
<script>
$( "#resizable" ).resizable();
</script>
</body>
</html>
There is an example given at http://www.rgraph.net/blog/2013/january/an-example-of-html5-canvas-drag-n-drop.html
I am not able to add multiple images into canvas 1 and move those added images to canvas 2. Also I should be able to drag(move the added image within canvas 2) those added images in second canvas.
function dragDrop(e, ui) {
// get the drop point (be sure to adjust for border)
var x = parseInt(ui.offset.left - offsetX) - 1;
var y = parseInt(ui.offset.top - offsetY);
// get the drop payload (here the payload is the $tools index)
var theIndex = ui.draggable.data("toolsIndex");
// drawImage at the drop point using the dropped image
ctx.drawImage($tools[theIndex], x, y, 32, 32);
}
http://jsfiddle.net/cyur7/
This jsfiddle link is working fine.
This solution uses the KineticJS library to accomplish your need.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/bSpBF/
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.1.min.js"></script>
<style>
body{ background-color: ivory; padding:10px;}
#container1,#container2{
border:solid 1px #ccc;
margin-top: 10px;
width:300px;
height:100px;
}
#container2{
height:300px;
}
</style>
<script>
$(function(){
var highlightWidth=8;
var stage = new Kinetic.Stage({
container: 'container1',
width: 300,
height: 100
});
var layer = new Kinetic.Layer();
stage.add(layer);
var dropzone = new Kinetic.Stage({
container: 'container2',
width: 300,
height: 300
});
var dropLayer = new Kinetic.Layer();
dropzone.add(dropLayer);
// these must go after the creation of stages & layers
addBackground(stage,layer,dropLayer);
layer.draw();
addBackground(dropzone,dropLayer,layer);
dropLayer.draw();
// get images & then trigger start()
var images={};
var URLs = {
house1: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-3.jpg',
house2: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-4.jpg',
house3: 'https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house204-1.jpg'
};
loadImages(URLs,start);
function start(){
var house1=kImage(images.house1,10,10,50,50,layer);
var house2=kImage(images.house2,75,10,50,50,layer);
var house3=kImage(images.house3,140,10,50,50,layer);
layer.draw();
}
function swapStagesIfSelected(sourceLayer,destinationLayer,startX,startY){
// get all elements on the source layer
var elements=sourceLayer.get("Image");
// don't let dropped elements fall off the stage
var totalWidth=0;
var maxHeight=-999;
var layerWidth=destinationLayer.getStage().getWidth();
var layerHeight=destinationLayer.getStage().getHeight();
for(var i=0;i<elements.length;i++){
if(elements[i].isSelected){
totalWidth+=elements[i].getWidth();
maxHeight=Math.max(elements[i].getHeight(),maxHeight);
}
}
if(startX+totalWidth>layerWidth){
startX=layerWidth-totalWidth-15;
}
if(startY+maxHeight>layerHeight){
startY=layerHeight-maxHeight-15;
}
// move all selected images
// to the clicked x/y of the destination layer
for(var i=0;i<elements.length;i++){
var element=elements[i];
if(element.isSelected){
var img=element.getImage();
kImage(img,startX,startY,element.getWidth(),element.getHeight(),destinationLayer);
startX+=element.getWidth()+10;
element.remove();
}
}
sourceLayer.draw();
destinationLayer.draw();
}
// build the specified KineticJS Image and add it to the specified layer
function kImage(image,x,y,width,height,theLayer){
var image=new Kinetic.Image({
image:image,
x:x,
y:y,
width:width,
height:height,
strokeWidth:0.1,
stroke:"green",
draggable:true
});
image.myLayer=theLayer;
image.isSelected=false;
image.on("click",function(){
highlight(this);
this.myLayer.draw();
});
image.myLayer.add(image);
return(image);
}
// build a background image and add it to the specified stage
function addBackground(theStage,theLayer,otherLayer){
var background = new Kinetic.Rect({
x: 0,
y: 0,
width: theStage.getWidth(),
height: theStage.getHeight(),
fill: "white",
stroke: "green",
strokeWidth: 1
});
background.on("click",function(){
var pos=theStage.getMousePosition();
var mouseX=parseInt(pos.x);
var mouseY=parseInt(pos.y);
swapStagesIfSelected(otherLayer,theLayer,mouseX,mouseY);
});
theLayer.add(background);
}
///////////// Image loader
function loadImages(URLs, callback) {
var loaded = 0;
var needed = 0;
for(var url in URLs) { needed++; console.log(url); }
for(var url in URLs) {
images[url] = new Image();
images[url].onload = function() {
if(++loaded >= needed) {
callback(images);
}
};
images[url].src = URLs[url];
}
}
///////////// Toggle Highlighting
function highlight(element,setStrokeWidth){
if(setStrokeWidth){
element.setStrokeWidth(setStrokeWidth);
}else{
if(element.getStrokeWidth()>5){
element.setStrokeWidth(0.1);
element.isSelected=false;
}else{
element.setStrokeWidth(highlightWidth);
element.isSelected=true;
}
}
}
}); // end $(function(){});
</script>
</head>
<body>
<p>Click on image(s) to toggle selection</p>
<p>Then click in the other canvas to drop</p>
<div id="container1"></div>
<div id="container2"></div>
<button id="clear">Clear Hightlights</button>
<button id="swap">Swap Selected</button>
</body>
</html>
I'm drawing a number of rectangles on an HTML5 canvas and want to be able to right click on the boxes and get a context sensitive menu displayed. The menu should be specific to the type of box being clicked on and be totally user specified, i.e. it should not include Reload, Save As, Print etc...
Can any one give me any pointers?
Thanks,
Paul
You can addEventListener for context menu to handle right-mouse requests:
// listen for contextmenu requests
canvas.addEventListener('contextmenu', handleContextmenu, false);
Then in the handler, you check each of your rects for hits:
function handleContextmenu(e){
// get mouse position relative to the canvas
var x=parseInt(e.clientX-offsetX);
var y=parseInt(e.clientY-offsetY);
// check each rect for hits
for(var i=0;i<rects.length;i++){
var rect=rects[i];
var rectRight=rect.x+rect.width;
var rectBottom=rect.y+rect.height;
// if this rect is hit, display an alert
if(x>=rect.x && x<=rectRight && y>=rect.y && y<=rectBottom ){
alert("Context menu request on the "+rect.color+" rectangle.");
}
}
// prevents the usual context from popping up
e.preventDefault()
return(false);
}
Here is working code (no jsFiddle because no right-clicking in X-Domain iframes):
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var rects=[];
rects.push({x:50,y:50,width:50,height:50,color:"red"});
rects.push({x:150,y:100,width:75,height:75,color:"blue"});
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<rects.length;i++){
var rect=rects[i];
ctx.beginPath();
ctx.fillStyle=rect.color;
ctx.rect(rect.x,rect.y,rect.width,rect.height);
ctx.fill();
}
// listen for contextmenu requests
canvas.addEventListener('contextmenu', handleMouseDown, false);
function handleMouseDown(e){
// get mouse position relative to the canvas
var x=parseInt(e.clientX-offsetX);
var y=parseInt(e.clientY-offsetY);
// check each rect for hits
for(var i=0;i<rects.length;i++){
var rect=rects[i];
var rectRight=rect.x+rect.width;
var rectBottom=rect.y+rect.height;
// check each rect for hits
if(x>=rect.x && x<=rectRight && y>=rect.y && y<=rectBottom ){
alert("Context menu request on the "+rect.color+" rectangle.");
}
}
// prevents the usual context from popping up
e.preventDefault()
return(false);
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
I have a question related to HTML5 canvas.
I am developing a game that requires the users to draw an image on the canvas.
The tools contain Text and Rectangle tools etc...
The color default value of the Text and Rectangle tools is black. So I have added more colors so the user can change the color of the font and the rectangle.
The problem is that: in the first time of using the tool, when the color is clicked the font's color remains black but if the user uses the text tool again, the font's color changed according to the selected color and the same with the rectangle, it is filled with black color first then when the user draws another rectangle. the color changed from black to the selected color.
How can I change the default value from the beginning???
Edited::
ok her is my code:
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
#clr div{
cursor:pointer;
cursor:hand;
width:20px;
height:20px;
float:left;
margin-right:10px;
}
#clr2 font{
cursor:pointer;
cursor:hand;
margin-top:100px;
margin-right:10px;
}
#clr3 font{
cursor:pointer;
cursor:hand;
margin-top:100px;
margin-right:10px;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript">
// Drawing options
var tool;
var tool_default = '';
function drawLine(){
// Get the tool select input.
var tool_select = document.getElementById('dtool');
if (!tool_select) {
alert('Error: failed to get the dtool element!');
return;
}
tool_select.addEventListener('change', ev_tool_change, false);
// Activate the default tool.
if (tools[tool_default]) {
tool = new tools[tool_default]();
tool_select.value = tool_default;
}
// Attach the mousedown, mousemove and mouseup event listeners.
layer3.addEventListener('mousedown', ev_canvas, false);
layer3.addEventListener('mousemove', ev_canvas, false);
layer3.addEventListener('mouseup', ev_canvas, false);
}
// The general-purpose event handler. This function just determines the mouse
// position relative to the canvas element.
function ev_canvas (ev) {
if (ev.layerX || ev.layerX == 0) { // Firefox
ev._x = ev.layerX;
ev._y = ev.layerY;
}
// Call the event handler of the tool.
var func = tool[ev.type];
if (func) {
func(ev);
}
}
// The event handler for any changes made to the tool selector.
function ev_tool_change (ev) {
if (tools[this.value]) {
tool = new tools[this.value]();
}
}
// This object holds the implementation of each drawing tool.
var tools = {};
// The drawing pencil.
//Draw Rectangle
tools.rectangle = function () {
var tool = this;
this.started = false;
this.mousedown = function (ev) {
tool.started = true;
tool.x0 = ev._x;
tool.y0 = ev._y;
context3.fillStyle="";
};
this.mousemove = function (ev) {
if (!tool.started) {
return;
}
var x = Math.min(ev._x, tool.x0),
y = Math.min(ev._y, tool.y0),
w = Math.abs(ev._x - tool.x0),
h = Math.abs(ev._y - tool.y0);
context3.clearRect(0, 0, layer3.width, layer3.height);
if (!w || !h) {
return;
}
$("#clr div").click(function(){
context3.fillStyle = $(this).css("background-color");
});
context3.fillRect(x, y, w, h);
};
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
img_update();
}
};
};
<canvas class="canvas3" id="layer3" width="500" height="200" style="border:1px solid"> </canvas>
<p><label> Drawing tool: <select id="dtool" onClick="drawLine()">
<option value="pencil">Pencil</option>
<option value="rectangle">Rectangle</option>
</select></label></p>
<div id="clr">
<p> </p>
<div style="background-color:white;"> </div>
<div style="background-color:red;"> </div>
<div style="background-color:green;"> </div>
<div style="background-color:orange;"> </div>
<div style="background-color:brown;"> </div>
<div style="background-color:#d2232a;"> </div>
</div>
</div>
<script type="text/javascript">
layer3 = document.getElementById("layer3");
context3 = layer3.getContext("2d");
</script>
</body>
</html>
You have to set the fillStyle before you call drawText, and it sounds like you are setting it afterwards.
Edit: In short it is happening because:
$("#clr div").click(function(){
context3.fillStyle = $(this).css("background-color");
});
Is put inside your mousemove. This means that this never gets to be attached until a mouseMove happens.
Instead, put the above code at the top level and not inside of your mousemove