返回介绍

Color and brush size

发布于 2025-02-27 23:45:55 字数 2300 浏览 0 评论 0 收藏 0

Assuming that users will want to draw in colors other than black and use different brush sizes, let’s add controls for those two settings.

In Chapter 18 , I discussed a number of different form fields. Color fields were not among those. Traditionally, browsers don’t have built-in support for color pickers, but in the past few years, a number of new form field types have been standardized. One of those is <input type="color"> . Others include "date" , "email" , "url" , and "number" . Not all browsers support them yet—at the time of writing, no version of Internet Explorer supports color fields. The default type of an <input> tag is "text" , and when an unsupported type is used, browsers will treat it as a text field. This means that Internet Explorer users running our paint program will have to type in the name of the color they want, rather than select it from a convenient widget.

This is what a color picker may look like:

A color field

controls.color = function(cx) {
  var input = elt("input", {type: "color"});
  input.addEventListener("change", function() {
    cx.fillStyle = input.value;
    cx.strokeStyle = input.value;
  });
  return elt("span", null, "Color: ", input);
};

Whenever the value of the color field changes, the drawing context’s fillStyle and strokeStyle are updated to hold the new value.

The field for configuring the brush size works similarly.

controls.brushSize = function(cx) {
  var select = elt("select");
  var sizes = [1, 2, 3, 5, 8, 12, 25, 35, 50, 75, 100];
  sizes.forEach(function(size) {
    select.appendChild(elt("option", {value: size},
                           size + " pixels"));
  });
  select.addEventListener("change", function() {
    cx.lineWidth = select.value;
  });
  return elt("span", null, "Brush size: ", select);
};

The code generates options from an array of brush sizes, and again ensures that the canvas’ lineWidth is updated when a brush size is chosen.

This is a book about getting computers to do what you want them to do. Computers are about as common as screwdrivers today, but they contain a lot more hidden complexity and thus are harder to operate and understand. To many, they remain alien, slightly threatening things.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文