简体   繁体   English

如何为html5画布添加喷漆工具?

[英]how to add spray paint tool for html5 canvas?

Currently I have made a pencil tool work and changed the pencil colour, but I would like to add a spray paint tool which lets you draw onto a canvas and also change the spray paint colour. 目前我已经制作了铅笔工具并更改了铅笔颜色,但我想添加一个喷漆工具,可以让你画在画布上,也可以改变喷漆颜色。

This is part of the JavaScript for the spray paint tool I have tried implementing, but I can't manage to make it work. 这是我尝试实现的喷漆工具的JavaScript的一部分,但我无法使其工作。

//spray paint tool
tools.spray = function () {

  var tool = this;
  this.started = false;

  this.mousedown = function (ev) {

    if (!tool.started) {
      return;
    }

    var len = 5 + ( Math.random() * 5 | 0 );

    for( var i = 0; i < len; ++i ) {
      context.beginPath();
      context.strokeStyle = CurrentColor;

      context.arc(
        mouseX + Math.cos( Math.random() * Math.PI * 2 ) * radius * Math.random(),
        mouseY + Math.sin( Math.random() * Math.PI * 2 ) * radius * Math.random(),
        1,
        0, Math.PI * 2, false
      );

      context.fill();
    }
  }, 33);
}

You can see the full code here . 你可以在这里看到完整的代码。

If anyone can help it will most appreciated. 如果有人可以提供帮助,将非常感谢。

http://jsbin.com/urubev/9/edit http://jsbin.com/urubev/9/edit

In your HTML you had some javascript code in your option values. 在您的HTML中,您的选项值中包含一些JavaScript代码。 They need to be changed to this: 他们需要改为:

<select id="dtool">
     <option value="pencil">Pencil</option>
     <option value="spray">Spray</option>
</select>

In the JS I just moved the code snippet you already provided to inside the spray object. 在JS中,我只是将您已经提供的代码片段移动到了喷雾对象中。

//These are the variables used throughout the javascript
//var points = new Array();
var outlineImage = new Image();
radius = 15
var colorPurple = "#cb3594"; //variable for purple colour 
var colorGreen = "#659b41"; //variable for green colour 
var colorYellow = "#ffcf33";//variable for yellow colour 
var colorBlack = "#000000";//variable for black colour 
var CurrentColor = colorBlack; //variable for current colour 

//used to change the colour of the drawing tool
function changeColor( color_code ) {
    CurrentColor =color_code;
}


//this function will allow you clear the canvas 
function clearCanvas(){
 context.clearRect(0, 0, canvas.width, canvas.height);
}

if (window.addEventListener) {
    window.addEventListener('load', function () {
        var canvas, context;

          // The active tool instance.
          var tool;
          var tool_default = 'spray';

        function init() {
            // Find the canvas element.
            canvas = document.getElementById('imageView');//this is used to get a element id for 'imageView' the cnavas
            if (!canvas) {
                alert('Error: I cannot find the canvas element!');//if it fails to get the canvas then it will diplay this error
                return;
            }

            if (!canvas.getContext) {
                alert('Error: no canvas.getContext!');//if it fails to get the context then it will diplay this error
                return;
            }


            // Get the 2D canvas context.
            context = canvas.getContext('2d');// used to get canavs context to '2d'
            if (!context) {
                alert('Error: failed to getContext!');//if it fails to get the context then it will diplay this error
                return;
            }

        // 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.
            canvas.addEventListener('mousedown', ev_canvas, false);
            canvas.addEventListener('mousemove', ev_canvas, false);
            canvas.addEventListener('mouseup', ev_canvas, false);
        }

 // 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 = {};

        // This painting tool works like a drawing pencil which tracks the mouse
        // movements.
         tools.pencil = function() {
            var tool = this;
            this.started = false;

            // This is called when you start holding down the mouse button.
            // This starts the pencil drawing.
            this.mousedown = function (ev) {
                context.beginPath();
                context.strokeStyle = CurrentColor;
                context.moveTo(ev._x, ev._y);
                tool.started = true;
            };

            // This function is called every time you move the mouse. Obviously, it only
            // draws if the tool.started state is set to true (when you are holding down
            // the mouse button).
            this.mousemove = function (ev) {
                if (tool.started) {
                    context.strokeStyle = CurrentColor;
                    context.lineTo(ev._x, ev._y);                   
                    context.stroke();
                }
            }; 

            // This is called when you release the mouse button.
            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                }
            };
        }

         tools.spray = function() {
            var tool = this;
            this.started = false;

            this.mousedown = function (ev) {
                context.beginPath();
                context.strokeStyle = CurrentColor;
                context.moveTo(ev._x, ev._y);
                tool.started = true;
            };

            this.mousemove = function (ev) {
                if (tool.started) {
                    context.strokeStyle = CurrentColor;

                    context.arc(
                        ev._x + Math.cos( Math.random() * Math.PI * 2 ) * radius * Math.random(),
                        ev._y + Math.sin( Math.random() * Math.PI * 2 ) * radius * Math.random(),
                        1,
                        0, Math.PI * 2, false
                    );
                    context.fill();
                }
            };

            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                }
            };
        }           

        // The general-purpose event handler. This function just determines the mouse
        // position relative to the canvas element.
        function ev_canvas(ev) {
            if (navigator.appName == 'Microsoft Internet Explorer' || navigator.vendor == 'Google Inc.' || navigator.vendor == 'Apple Computer, Inc.') { // IE or Chrome
                ev._x = ev.offsetX;
                ev._y = ev.offsetY;
            } else if (ev.layerX || ev.layerX == 0) { // Firefox
                ev._x = ev.layerX - this.offsetLeft;
                ev._y = ev.layerY - this.offsetTop;
            } else if (ev.offsetX || ev.offsetX == 0) { // Opera
                ev._x = ev.offsetX;
                ev._y = ev.offsetY;
            }
            // Call the event handler of the tool.
            var func = tool[ev.type];
            if (func) {
                func(ev);
            }
           // points.push(ev);
        }

        init();

    }, false);
    }

Here's my attempt. 这是我的尝试。 Added the following code: 添加了以下代码:

  tools.spray = function(){};
  tools.spray.prototype = new tools.pencil(); 
  tools.spray.prototype.mousemove = function (ev) {
    if (tool.started) {
      context.fillStyle = CurrentColor;
      context.rect(ev._x, ev._y, 1, 1);     

      for (var i = 20; i--;) { 
        context.rect(ev._x + Math.random() * 20 - 10, 
                     ev._y + Math.random() * 20 - 10, 1, 1);
        context.fill();
      }

    }
  };

First, we extend the "pencil" tool, since only the mousemove function differs. 首先,我们扩展“铅笔”工具,因为只有mousemove功能不同。 We do that by creating an instance of the pencil tool and using it as the prototype for our spray constructor function. 我们通过创建铅笔工具的实例并将其用作spray构造函数的原型来实现。 Then we overwrite the mousemove function, as above. 然后我们覆盖mousemove函数,如上所述。

The logic there is pretty simple, just create 20 dots in a square area around the mouse as it moves. 逻辑非常简单,只需在鼠标移动时在鼠标周围的正方形区域中创建20个点。 It would be better to use a round area, as in your original code, and allow the user to configure some parameters instead of using magic numbers (20 and rand(20) - 10). 最好使用圆形区域,就像在原始代码中一样,并允许用户配置一些参数而不是使用幻数(20和rand(20) - 10)。 But, for the sake of simplicity, it is what it is. 但是,为了简单起见,它就是它的本质。


As mentioned in the other answer, options needed to be changed like so: 正如在另一个答案中提到的,选项需要像这样改变:

  <option value="pencil">Pencil</option>
  <option value="spray">Spray</option>

Here's a cool barbed wire thing too, just for fun. 这里也是一个很酷的铁丝网,只是为了好玩。

  tools.barb = function(){};
  tools.barb.prototype = new tools.pencil(); 
  tools.barb.prototype.mousemove = function (ev) {
    if (tool.started) {
      context.strokeStyle = CurrentColor;
      context.lineTo(ev._x, ev._y);         
      context.lineTo(ev._x + Math.random() * 20 - 10, 
                     ev._y + Math.random() * 20 - 10);              
      context.stroke();
    }
  };

http://jsbin.com/awiyan/3/edit http://jsbin.com/awiyan/3/edit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM