Hardware and software setup

Coloring objects. Script for recoloring vector objects in the color of the background lying under it (testing completed) Application for mobile devices

In this note, I want to present another JavaScript creation of mine: Color Picker - a color picker. The script is quite simple in terms of functionality and installation, well, in principle, its code is also not very complicated. It does NOT use jQuery and images, is small in size, and is quite simple and fast. Works in IE 6-9, Opera, FireFox, Safari, Chrom.

The Color Picker by default generates a palette of 216 web-safe colors, and has a CSS-styled look, but the look and contents of the palette are customizable. Below are a couple of examples of what he can do.

The script has been updated to version 1.2 (the button for closing the palette has been added), but the listings have remained the same. A new version only in the archive.

Color Picker demo

The script archive with examples can be downloaded here:
colorPicker.v1.1 (Original version)
colorPicker.v1.2 (Added a button that closes the palette)

I will introduce some definitions to make it easier for me to explain to you:

Palette

The palette itself containing color swatches

Sample

A palette element that, when clicked, selects a color.

Picker

This is a square with a color that the user sees, and which he needs to click on in order for the color palette to appear.

Color Picker integration

The script is pretty easy to use. Color Picker - has a total of three available methods(shown with data type):

ColorPicker.insertInto(HTMLElement element, string name, string selected, int offsX, int offsY)

The main method - inserts a Color Picker into the specified html element. Parameters:

  1. element element- The DOM node - the tree in which to place the Color Picker
  2. string name- the name of the form element that will represent the selected color*
  3. string selected- string like "#FFCC00" - default picker color
  4. int offsX- offset of the palette coordinates (upper right corner) relative to the mouse click horizontally
  5. int offsY- offset of the palette coordinates (upper right corner) relative to the mouse click vertically

* - The Color Picker itself creates a hidden INPUT element and places it in the DOM before the picker. If you don't specify a name explicitly, the script will try to set the name of the hidden INPUT element to be the same as the id of the element specified in the first parameter.

// Add to page: ColorPicker.insertInto(document.getElementById("color_picker_two"), "base_color", "#0000ff", 10, 15); ColorPicker.setPallete(array arrayOfColors)

Allows you to set your own color palette. It takes a parameter - an array, for example:

ColorPicker.setPallete(["#FFFFFF","#FFCC00","#00FFCC","#0000FF","#00CCFF","#CC00FF"]); ColorPicker.setClasses(string picker, string palette, string colorItem)

Allows you to specify custom style class names for the picker, palette, and color swatches, for example:

ColorPicker.setColors("col-safe-picker","col-safe-palette","col-safe-item");

This will be required when you want to set your own color palette or change the appearance of the standard ones.

Color Picker usage example

The first thing we need is a form - in two of its elements we will insert Color Pickers:

We connect the main Color Picker file - a

Let's add styles to the standard palette:

In fact, only three classes are needed for the Color Picker: for the picker itself, for the palette, and for samples. For expressiveness, for the color swatches, we've added another pseudo-class... :hover That's all.

I hope I explained it in an accessible way, you can download the script files from the link at the beginning of the article, but I give a listing of the script to the heap - as always, I tried to be simpler and shorter if you have any questions, write.

Color Picker Listing

var ColorPicker = (function (GLOB) ( "use strict"; var DOC = GLOB.document, pickerClass = "col-pic-picker", paletteClass = "col-pic-palette", colorItemClass = "col-pic-item" , PALETTE = , // Creates a DOM element for the color swatch getColorItem = function (clickHandler) ( var colDiv = DOC.createElement("DIV"); colDiv.className = colorItemClass; colDiv.onclick = clickHandler; return colDiv; ), / / Get page scroll: pageScroll = function() ( return ( y: GLOB.pageYOffset || DOC.documentElement.scrollTop || DOC.body.scrollTop, x: GLOB.pageXOffset || DOC.documentElement.scrollLeft || DOC.body .scrollLeft ) ), // Generating a palette of colors (using 216 Safe Web Colors) // This function is not accessible from outside createPalette = function (srcPicker, srcInput) ( var palette = DOC.createElement("DIV"), length = PALETTE.length, hexR = "", hexG = "", hexB = "", colItem = null, i, q, m, // Sample click handler: clickHandler = function () ( srcPicker.styl e.background = this.style.background; srcInput.value = this.hv; palette.style.display = "none"; ), // Adds a color swatch to the palette: addColor = function (color) ( colItem = getColorItem(clickHandler); colItem.style.background = colItem.hv = color; palette.appendChild(colItem); ); // If the user has not set his palette: if (length === 0) ( // Generate the Safe Web Colors palette: for (i = 0x0; i<= 0xff; i += 0x33) { hexR = (i >0) ? i.toString(16) : "00"; for (q = 0x0; q<= 0xff; q += 0x33) { hexG = (q >0) ? q.toString(16) : "00"; for (m = 0x0; m<= 0xff; m += 0x33) { hexB = (m >0) ? m.toString(16) : "00"; addColor("#" + hexR + hexB + hexG); ) ) ) // Otherwise, if the user has entered his array of colors - display it: ) else ( for (i = 0; i< length; i += 1) { addColor(PALETTE[i]); } } // Конфиг палитры: palette.className = paletteClass; palette.style.display = "none"; palette.style.position = "absolute"; // Добавляем в DOM DOC.body.appendChild(palette); return palette; }; return { /** * Установка имён классов стилей. * @param string picker - Имя класса для значка выбора цвета, по-умолчанию: "col-pic-picker". * @param string palette - Имя класса для появляющейся палитры, по-умолчанию: "col-pic-palette". * @param string colorItem - Имя класса элементов - образцов цвета в палитре, для по-умолчанию: "col-pic-item". * @return ColorPicker */ setClasses: function (picker, palette, colorItem) { pickerClass = picker; paletteClass = palette; colorItemClass = colorItem; return this; }, /** * Установка своей палитры цветов. * @param array arrayOfColors - массив HEX-значений цветов. * @return ColorPicker */ setPallete: function (arrayOfColors) { PALETTE = arrayOfColors; return this; }, /** * Вставить выбиралку цвета в HTMLElement * @param HTMLElement element - элемент, результат выборки: document.getElementById * @param string name - атрибут для элемента формы, представляющего выбранный цвет. * @param string selected - значение по-умолчанию для элемента формы, представляющего выбранный цвет. * @param int offsX - смещение палитры относительно эемента выбора цвета по горизонтали * @param int offsY - смещение палитры относительно эемента выбора цвета по вертикали * @return ColorPicker */ insertInto: function (element, name, selected, offsX, offsY) { var picker = DOC.createElement("DIV"), hideInput = DOC.createElement("INPUT"), palette = createPalette(picker, hideInput), oX = offsX || 1, oY = offsY || 1; // Скрытый элемент формы, значение которого // будет меняться, в зависимости от выбора цвета // и которое будет передаваться на сервер. hideInput.value = picker.style.background = selected; hideInput.type = "hidden"; hideInput.name = name || element.id; picker.className = pickerClass; // Обработчик клика на элементе - пикере picker.onclick = function (ev) { var e = ev || GLOB.event, x = e.clientX, y = e.clientY; palette.style.display = "block"; palette.style.top = (y + pageScroll().y) - oY + "px"; palette.style.left = (x + pageScroll().x) + oX + "px"; }; // Добавляем в DOM element.appendChild(picker); element.insertBefore(hideInput, picker); return this; } }; }(this));

Today we present a useful script for Adobe Illustrator. It was created by a talented Ukrainian developer of scripts and plugins for Adobe Illustrator and my friend - Yaroslav Tabachkovsky (Yemz), who is also known as the developer of the free Mesh Tormentor plugin. The RandomSwatchesFill script randomly paints selected objects with the colors selected in the Swatches palette.

You can download the script for free by clicking on the Download button at the beginning or end of this review.

Let's place the script in the following folder, for example:

For Windows: C:\Program Files\Adobe\Adobe Illustrator CS5\Presets\en_GB\Scripts

For Mac: Applications / Adobe\Adobe Illustrator CS5\Presets\en_GB\Scripts

For an example of the work of the Random Swatches Fill script, let's take a vector work consisting of many one-color objects.

I draw your attention to the fact that the objects to which the script will be applied must be ungrouped and selected. Without deselecting, open the Swatches panel. Using the Ctrl/Command key, select the colors from the Swatches palette that we will use to color the objects.

We use the RandomSwatchesFill script, for this we go to File > Scripts > RandomSwatchesFill. As a result, we get colored objects painted randomly.

This script can be applied both to the entire vector work and to several objects. Using the Lasso Tool (Q), select a few objects and using the Ctrl/Command key, select colors from the Swatches palette to color these objects with.

As a result, a part of the vector work is colored randomly with the selected colors.

You can experiment with colors, gradient fills or patterns in the Swatches panel and see what original results you can achieve. On my own behalf, I want to thank Yemz for this script and I hope that it will be useful in your daily creative work and you will spend less time on routine technical issues.

Personally, I have applied given script, when creating your new call order plugin. This palette helps the user to select the color of the button and the order form. For a long time I selected the right script and as for me this one is one of the best. Besides, as I said, it is easily implanted. An example of what you get as a result can be seen in the example below. Select a color with the cursor on the fields with a gradient.

To make such a palette, you need to take 4 steps. Let's start in order with markup HTML. You need to add it to where you want to see the palette itself.

Main parent block with id - color-picker. It contains three main blocks, which inside have child elements, which creates the structure of our palette. Let's take them in order, relative to the image below.

  1. block with id picker-wrapper is the first block. Responsible for drawing a square with a gradient of one color to choose its hue. Inside it is a block with the gradient itself and a block responsible for the pointer.
  2. block with id pcr-wrapper- the second block responsible for the block that displays all the colors in the form of a gradient. Inside is a block with a gradient and a block that displays a slider that moves up and down.
  3. UL list with id color-values- There are several points inside it. The first three, in the diagram they are numbered - 3. They display color codes in three formats - RGB, HSV, HEX.
  4. The block in the picture, which is number 4, is one of the elements of the previous list. This is the last li item. Inside it is a block with ID pcr_bg. This block displays the currently selected color.

You can, depending on your needs, swap or even remove those elements that are not needed. When we are completely done with the installation of the palette, then you will be able to figure it out in more detail yourself and determine how to change one or another element of the palette.

The second step to install the palette is to add styles. css. You add them, as usual, to the style file of your site, or of the element to which you connect this color palette.

#color-picker( margin:25px auto; width:450px; ) #color-values( display:block; list-style:none; color:#222; float:left; margin:0 0 0 15px; padding: 5px; text-align:left; ) #pcr_bg( height:135px; ) .picker-wrapper, .pcr-wrapper ( position: relative; float: left; ) .picker-indicator, .pcr-indicator ( position: absolute; left: 0; top: 0; ) .picker, .pcr ( cursor: crosshair; float: left; ) .cp-default .picker ( width: 200px; height: 200px; ) .cp-default .pcr ( width: 30px; height : 200px; ) .cp-default .pcr-wrapper ( margin-left: 10px; ) .cp-default .picker-indicator ( width: 5px; height: 5px; border: 2px solid darkblue; -moz-border-radius: 4px; -o-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px; opacity: .5; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)" ;filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=50); filter: alpha(opacity=50); background-color: white; ) .cp-default .pcr-indicator ( width: 100%; height: 10px; lef t: -4px opacity: .6; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=60)"; filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=60); filter: alpha(opacity=60); border: 4px solid lightblue; -moz-border-radius: 4px; -o-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px background color: white )

I won't write about CSS. As I said, it is unlikely that a beginner will set a palette, but an experienced one is familiar with CSS. I think you will understand which parameter is responsible for what. Let's move on to the next step.

The third point that you must do is to include a file that contains the color palette script itself. The file itself will be in the archive with the sources of this article. You can download it from the link below.

The file is called colorpicker.min.js. Connect it in the header or in the footer of the site, if you will display the palette on the site. If in some module, plugin, etc., then where you connect the rest of the scripts. Naturally, specify the correct path to the file.

Well, the last step is to connect a script that will control the output of the palette values, well, and start its work as such. The script is best connected immediately after the palette block with HTML.

There are several things that can be configured in the script. Let's break them down. What can be changed starts from the 9th line.

  • 9th line - block with id - hex, the color value is assigned in hex format. That is, in the list, which is number 3 in the picture above, the first line. Thus, you can assign a color code to any block to display it.
  • 10th line - block with id - rgb, assigns a value in rgb format. Everything is similar to the previous paragraph.
  • 11th line - block with id - hsv, assigns a value in hsv format.
  • 13th line - block with id - pcr_bg, the style is assigned, in the form of a background corresponding to the hex format. That is to say, the square that shows the current color. In a similar way, you can display color from the palette, for example, for the background of a site of a certain block, and so on.
  • The 15th, last line, sets the default color. You can specify your own, in hex format.

That's essentially the whole connection color palette. As I said at the very beginning, this article may not help a beginner, it is designed for more experienced webmasters. I hope she helps you.

That's all, thanks for your attention. 🙂

an object . The button name is btn.cvet). For key frame let's create a script:

var cvet: ColorTransform = rol.transform.colorTransform; btn.cvet.addEventListener(MouseEvent.CLICK, f); function f(event:MouseEvent):void ( cvet.color = 0x0000ff; rol.transform.colorTransform = cvet )

Changes in the script can be made in the following fragments highlighted in red: the name of the movie (rol), button (btn.cvet), variable (cvet), function (f) and color value (0000ff).

Let's analyze the above script:

  • The rol (as well as all symbols) has a transform property that contains information about the various transformations applied to the object (such as geometric transformations, color settings). To apply transformations related to setting the color of an object, use the colorTransform property.
  • The new variable cvet created is set to the value of the movie properties rol related to color settings.
  • We change the color value of the color property to a new one:

    0000ff is the RGB hexadecimal representation of red, green, and blue colors are given as two-digit numbers in hexadecimal code (in hexadecimal code, Arabic numerals 0-9 are used, and Latin letters a, b, c, d, e, f, acting as analogues of numbers 10, 11, 12, 13, 14 and 15 ). The final color of the object is obtained by mixing three colors in the specified proportions.

  • Update the colorTransform property of the rol object (perform color correction).

Practical work No. 1

Let's create a movie on the stage (an object for coloring - named rol) and 2 buttons (btn.cvet1 and btn.cvet2), symbolizing 2 colors in the color palette. Clicking on each button paints the video in the color assigned to the button. Appearance buttons should talk about their purpose (for example, the color of the buttons corresponds to the color of the object being painted).

In the script, you will need to create a variable to read the color of the object and set one of two colors for it, depending on the button pressed:

var cvet:ColorTransform = rol.transform.colorTransform; btn.cvet1.addEventListener(MouseEvent.CLICK, f1); function f1(event:MouseEvent):void ( cvet.color = 0x0000ff; rol.transform.colorTransform = cvet; ) btn.cvet2.addEventListener(MouseEvent.CLICK, f2); function f2(event:MouseEvent):void ( cvet.color = 0x00ff00; rol.transform.colorTransform = cvet; )

Practical work №2

Let's create 2 buttons on the scene (objects for coloring - named rol1, rol2) and 2 buttons (symbolizing 2 colors in the color palette - named btn.cvet1 and btn.cvet2). Pressing the color palette button - color selection; clicking on the buttons-objects for coloring leads to coloring them in the color selected earlier in a step. The appearance of the color palette buttons should indicate their purpose.

There are 2 steps to coloring an object:

  • choose a color;
  • select an object to be painted in the selected color.

    var cvet:ColorTransform = rol1.transform.colorTransform; btn.cvet1.addEventListener(MouseEvent.CLICK, f1); function f1(event:MouseEvent):void ( cvet.color = 0x0000ff; ) btn.cvet2.addEventListener(MouseEvent.CLICK, f2); function f2(event:MouseEvent):void ( cvet.color = 0x00ff00; ) rol1.addEventListener(MouseEvent.CLICK, f3); function f3(event:MouseEvent):void ( rol1.transform.colorTransform = cvet; ) rol2.addEventListener(MouseEvent.CLICK, f4); function f4(event:MouseEvent):void ( rol2.transform.colorTransform = cvet; )

Coloring objects without analyzing the coloring of various objects, as a rule, does not make sense. When creating an application that uses object coloring as a selection tool for a given object, it is necessary to analyze the colors received by the objects in the course of work. Exists software object color analysis.

We will consider an example of a task in which color analysis is performed by "remembering" the selected color for coloring a figure (and not by "analyzing" the color of an already painted figure).

Suppose it is necessary from the set geometric shapes mark squares, triangles and rhombuses like this: color squares with one color, triangles with another, etc.


Rice. 22.1. Color Analysis Application Interface

The script declares type variables number:

  • c (for storing information about the selected color),
  • fla.1, fla.2, fla.3 (to store information about the color received by each circle).

The "Check" button (its name is pr) and a dynamic text field (ttt) are placed on the stage, in which information about the correctness / incorrectness of the coloring of the circles is displayed.

In the case of correct coloring of all shapes (the logical expression in the branch command will be true when all three simple boolean expressions– first and (&&) second and (&&) third) the text property of the ttt dynamic text field is set to "verno", otherwise it is set to "ne verno":

... pr.addEventListener(MouseEvent.CLICK, f7); function f7(event:MouseEvent):void ( if ((fla.1==1) && (fla.2==2) && (fla.3==3)) ( ttt.text = "verno"; ) else ( ttt.text = "ne verno"; ) )

Brief summary of the lecture:

The symbol has a transform property that contains information about the various transformations applied to the object (such as geometric transformations, color settings). To apply transformations related to setting the color of an object, use the colorTransform property.

I think this block will be very useful, especially for cases when you need to embed it on your site. This Color Picker block works with Javascript. So let's look at how to add it to the site and what is remarkable about this JQuery plugin.

Working with code

First of all, we need to include Javascript and css file s. Don't forget to edit the CSS file and fix the image paths (if needed) to match the theme of your site.

XHTML

Plugin settings

Custom plugin settings (optional).

  • eventName - the desired event to call the color picker, default: "click".
  • color is the default color. String for hex colors or hash for RGB and HSB ((r:255, r:0, b:0)), default: “FF0000″.
  • flat - display the color picker immediately or only on click, default value is false .
  • livePreview - true by default.
  • onShow - The callback function fires when the color picker is shown.
  • onBeforeShow - The callback function fires before the color picker has been shown.
  • onHide - The callback function fires when the color picker is hidden.
  • onChange - The callback function fires when the color changes.
  • onSubmit - The callback is fired when a color is selected.

Hope you enjoy this plugin. I wish you success and development of your site!

This lesson was prepared for you by the site team
Lesson source: http://www.eyecon.ro/colorpicker/
Translated by: Vladislav Bondarenko

Liked the article? Share with friends!
Was this article helpful?
Yes
Not
Thanks for your feedback!
Something went wrong and your vote was not counted.
Thank you. Your message has been sent
Did you find an error in the text?
Select it, click Ctrl+Enter and we'll fix it!