Home > Web Front-end > JS Tutorial > body text

js implements brush function notes through canvas

PHP中文网
Release: 2017-07-14 10:26:33
Original
2732 people have browsed it

I believe everyone is familiar with the line drawing function of flash. I have written similar functions using flash's actionscript before. However, considering that flash is already an obsolete technology,

Below we introduce how to implement the drawing board function through the canvas tag of html5 combined with javascript. The

code is as follows:

<script src="http://www.php.cn/static/home/js/jquery.min.js"></script>
<canvas id="paintcanvas" width="600" height="700"></canvas>
<script>
var paint;
var clickX=[];
var clickY=[];
var clickDrag=[];
function addClick(x,y,dragging)
{
        clickX.push(x);
        clickY.push(y);
        clickDrag.push(dragging);
}
function redraw()
{
        paintcanvas.strokeStyle = "#df4b26";
        paintcanvas.lineJoin = "round";
        paintcanvas.lineWidth = 5;
        for(var i=0; i < clickX.length; i++)
        {
            paintcanvas.beginPath();
            if(clickDrag[i] && i){//当是拖动而且i!=0时,从上一个点开始画线。
                paintcanvas.moveTo(clickX[i-1], clickY[i-1]);
            }else{
                paintcanvas.moveTo(clickX[i]-1, clickY[i]);
            }
            paintcanvas.lineTo(clickX[i], clickY[i]);
            paintcanvas.closePath();
            paintcanvas.stroke();
        }
}
paintcanvas=$(&#39;#paintcanvas&#39;)[0].getContext("2d");
$(&#39;#paintcanvas&#39;).mousedown(function(e){
        var mouseX=e.pageX-this.offsetLeft;
        var mouseY=e.pageY-this.offsetTop;
        paint=true;
        addClick(e.pageX-this.offsetLeft,e.pageY-this.offsetTop);
        redraw();
});
$(&#39;#paintcanvas&#39;).mousemove(function(e){
        if(paint){
            addClick(e.pageX-this.offsetLeft,e.pageY-this.offsetTop,true);
            redraw();
        }
});
$(&#39;#paintcanvas&#39;).mouseup(function(e){
        paint = false;
});
$(&#39;#paintcanvas&#39;).mouseleave(function(e){
        paint = false;
});
</script>
Copy after login

Among them , the line drawing function is realized through mousedown, mousemove, mouseup, mouseleave and other js events.

This article is provided by php Chinese website,

Original address: http://www.php.cn/js-tutorial-374130.html

Please do not reprint~~ ~~

The above is the detailed content of js implements brush function notes through canvas. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template